<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>Regexp::Grammars - Add grammatical parsing features to Perl 5.10 regexes - metacpan.org</title>
        <link rel="preload" as="fetch" href="https://metacpan.org/account/login_status" crossorigin="anonymous" />
        <link href="https://metacpan.org/_assets/b8ccceeed47a0652049703d99326a9cea4933443.css" rel="stylesheet" type="text/css">
        <script src="https://metacpan.org/_assets/6bfedafe2d7caa915b7d84f61b45936818e3242e.js" type="text/javascript" defer></script>
        <link rel="alternate" type="application/rss+xml" title="Recent CPAN Uploads of Regexp-Grammars - MetaCPAN" href="https://metacpan.org/dist/Regexp-Grammars/releases.rss" />
        <link rel="canonical" href="./Regexp::Grammars.html" />
        <meta name="description" content="Add grammatical parsing features to Perl 5.10 regexes" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5">
        <link rel="shortcut icon" href="https://metacpan.org/static/icons/favicon.ico">
        <link rel="apple-touch-icon" sizes="152x152" href="https://metacpan.org/static/icons/apple-touch-icon.png">
        <link rel="search" href="https://metacpan.org/static/opensearch.xml" type="application/opensearchdescription+xml" title="MetaCPAN">
        <script>
          (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
          (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
          })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

          (function(skey, ga_id){
            ga('create', ga_id, {
              siteSpeedSampleRate : 100,
              storage             : 'none',
              clientId            : localStorage.getItem(skey)
            });
            ga(function(tracker) {
              localStorage.setItem(skey, tracker.get('clientId'));
            });
            ga('send', 'pageview');
          })('ga:clientId', 'UA-27829474-1');
        </script>
<meta name="twitter:card"        content="summary" />
<meta name="twitter:url"         content="https://metacpan.org/pod/Regexp::Grammars" />
<meta name="twitter:title"       content="Regexp::Grammars" />
<meta name="twitter:description" content="Add grammatical parsing features to Perl 5.10 regexes" />
<meta name="twitter:site"        content="metacpan" />
    </head>
    <body>
        <nav class="navbar navbar-default" role="navigation">
            <div class="header-logo-large hidden-xs">
              <a href="https://metacpan.org/" tabindex="0">
                <svg class="logo" aria-label="MetaCPAN">
                  <use class="logo" href="/static/images/metacpan-logo.svg#logo" />
                </svg>
              </a>
            </div>
            <div class="header-logo-icon visible-xs">
              <a href="https://metacpan.org/">
                <svg class="logo" aria-label="MetaCPAN">
                  <use class="logo" href="/static/images/metacpan-logo.svg#dots" />
                </svg>
              </a>
            </div>
            <ul class="nav navbar-nav menu-items hidden-xs hidden-sm">
              <li><a href="https://metacpan.org/about">About</a></li>
              <li><a href="https://metacpan.org/about/sponsors">Sponsor</a></li>
              <li><a href="https://grep.metacpan.org/">grep::cpan</a></li>
              <li><a href="https://metacpan.org/recent">Recent</a></li>
              <li><a href="https://metacpan.org/about/faq">FAQ</a></li>
              <li><a href="https://metacpan.org/tools">Tools</a></li>
              <li><a href="https://fastapi.metacpan.org/">API</a></li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <button type="button" class="searchbar-btn visible-xs visible-sm">
                    <i class="fa fa-search button-fa-icon"></i>
                </button>
                <form action="https://metacpan.org/search" class="searchbar-form visible-md visible-lg search-form form-horizontal">
                   <input type="hidden" name="size" id="metacpan_search-size" value="20">
                  <div class="form-group">
                      <div class="search-group">
                        <i class="fa fa-search"></i>
                        <input type="text" name="q" placeholder="Search the CPAN" size="41" autocorrect="off" autocapitalize="off" spellcheck="false" id="metacpan_search-input" class="form-control" value="">
                      </div>
                  </div>
                </form>
                    <li class="icon-slidepanel visible-xs visible-sm">
                      <button data-toggle="slidepanel" data-target=".slidepanel">
                        <span class="button-fa-icon">
                          <i class="fa fa-bars slidepanel-open"></i>
                          <i class="fa fa-times slidepanel-close"></i>
                        </span>
                      </button>
                    </li>
                <form action="https://metacpan.org/account/logout" method="POST" id="metacpan-logout"></form>
                <li class="dropdown logged_in" style="display: none;">
                    <button type="button" class="dropdown-toggle" data-toggle="dropdown">
                      <i class="fa fa-user button-fa-icon logged-in-icon" aria-hidden="true"></i>
                      <i class="fas fa-chevron-down"></i>
                    </button>
                    <ul class="dropdown-menu">
                        <li><a href="https://metacpan.org/account/identities">Identities</a></li>
                        <li><a href="https://metacpan.org/account/profile">Profile</a></li>
                        <li><a href="https://metacpan.org/account/favorite/list">Favorites</a></li>
                        <li>
                            <a href="./Regexp::Grammars.html#" type="button" onclick="$('#metacpan-logout').submit(); return false">
                              Logout
                            </a>
                        </li>
                    </ul>
                </li>
                <li class="dropdown logged_out" style="display: none;">
                    <button type="button" class="dropdown-toggle" data-toggle="dropdown">
                      <i class="fa fa-user button-fa-icon" aria-hidden="true"></i>
                      <i class="fas fa-chevron-down"></i>
                    </button>
                    <ul class="dropdown-menu">
                        <li>
                            <a href="https://metacpan.org/login/github">
                                <i class="fab fa-github fa-fw"></i>
                                GitHub
                            </a>
                        </li>
                        <li>
                            <a href="https://metacpan.org/login/twitter">
                                <i class="fab fa-twitter fa-fw"></i>
                                Twitter
                            </a>
                        </li>
                        <li>
                            <a href="https://metacpan.org/login/google">
                                <i class="fab fa-google fa-fw"></i>
                                Google
                            </a>
                        </li>
                    </ul>
                </li>
                <li class="dropdown logged_placeholder">
                    <button>
                      <i class="fa fa-user button-fa-icon" aria-hidden="true"></i>
                    </button>
                </li>
            </ul>
        </nav>
        <div class="page-content ">
          <!--
          <div class="top-notify-banner">
            <i class="fas fa-info-circle"></i>
          </div>
          -->
          <nav class="sidebar">
            <div class="slidepanel">
              <ul class="nav-list ">
    <li class="nav-header no-margin-top">
      <div class="ttip" data-toggle="tooltip" data-placement="bottom" title="The date that this version of Regexp-Grammars was released.">
      <span class="relatize">15 Sep 2022 01:31:42 UTC</span>
    </li>
  <li>
    Distribution: <a href="https://metacpan.org/dist/Regexp-Grammars">Regexp-Grammars</a>
  </li>
  <li>
    Module version: 1.058
  </li>
  <li>
    <a data-keyboard-shortcut="g s" href="https://metacpan.org/dist/Regexp-Grammars/source/lib/Regexp/Grammars.pm">Source</a>
    (<a href="https://metacpan.org/dist/Regexp-Grammars/source/lib/Regexp/Grammars.pm?raw=1">raw</a>)
  </li>
  <li>
    <a data-keyboard-shortcut="g b" href="https://metacpan.org/dist/Regexp-Grammars/source/lib/Regexp">Browse</a>
    (<a href="https://metacpan.org/dist/Regexp-Grammars/source/lib/Regexp?raw=1">raw</a>)
  </li>
    <li>
      <a data-keyboard-shortcut="g c" href="https://metacpan.org/dist/Regexp-Grammars/changes">Changes</a>
    </li>
    <li>
      <a class="nopopup" href="https://metacpan.org/dist/Regexp-Grammars/contribute">How to Contribute</a>
    </li>
    <li>
      <a rel="noopener nofollow" data-keyboard-shortcut="g i" href="https://rt.cpan.org/Public/Dist/Display.html?Name=Regexp-Grammars">Issues</a>
      (46)
    </li>
    <li>
      <a rel="noopener nofollow" href="http://matrix.cpantesters.org/?dist=Regexp-Grammars+1.058" title="Matrix">Testers</a>
        <span title="(pass / fail / na)">(<a rel="noopener nofollow" href="https://www.cpantesters.org/distro/R/Regexp-Grammars.html?oncpan=1&amp;distmat=1&amp;version=1.058&amp;grade=2" style="color: #090">3131</a> / <a rel="noopener nofollow" href="https://www.cpantesters.org/distro/R/Regexp-Grammars.html?oncpan=1&amp;distmat=1&amp;version=1.058&amp;grade=3" style="color: #900">100</a> / <a rel="noopener nofollow" href="https://www.cpantesters.org/distro/R/Regexp-Grammars.html?oncpan=1&amp;distmat=1&amp;version=1.058&amp;grade=4">3</a>)</span>
    </li>
    <li>
      <a rel="noopener nofollow" href="http://cpants.cpanauthors.org/release/DCONWAY/Regexp-Grammars-1.058">Kwalitee</a>
    </li>
    <li>
      <div class="ttip" data-toggle="tooltip" data-placement="bottom" title="The # people with an indexing permission on Regexp-Grammars who have released something to CPAN in the last 2 years (i.e. the # people likely able to release critical fixes in a timely manner)">
      Bus factor: 1
      </div>
    </li>
    <li>
      <a rel="noopener nofollow" href="http://cpancover.com/latest/Regexp-Grammars-1.058/index.html">61.57% Coverage </a>
    </li>
    <li>
      License: perl_5
    </li>
    <li class="nav-header">Activity</li>
    <li>
<div class="activity-graph">
    <img src="https://metacpan.org/dist/Regexp-Grammars/activity.svg?res=month" />
    <div class="comment">24 month</div>
</div>
    </li>
    <li class="nav-header">Tools</li>
    <li>
      <a itemprop="downloadUrl" href="https://cpan.metacpan.org/authors/id/D/DC/DCONWAY/Regexp-Grammars-1.058.tar.gz">
      Download (<span itemprop="fileSize">259.56KB</span>)</a>
    </li>
    <li>
      <a href="https://explorer.metacpan.org/?url=%2Fmodule%2FDCONWAY%2FRegexp-Grammars-1.058%2Flib%2FRegexp%2FGrammars.pm">
        MetaCPAN Explorer
      </a>
    </li>
    <li>
      <a href="https://metacpan.org/dist/Regexp-Grammars/permissions">
        Permissions
      </a>
    </li>
    <li>
      <a href="https://metacpan.org/dist/Regexp-Grammars/releases.rss">
        Subscribe to distribution
      </a>
    </li>
    <li>
      <button class="btn btn-link" data-toggle="modal" data-target="#metacpan_install-instructions-dialog">
        Install Instructions
      </button>
    </li>
    <li>
      <form action="https://metacpan.org/search">
        <input type="hidden" name="q" value="dist:Regexp-Grammars">
        <input type="search" name="q" placeholder="Search distribution" class="form-control tool-bar-form">
        <input type="submit" style="display: none">
      </form>
    </li>
    <li>
      <form action="https://grep.metacpan.org/search">
        <input type="hidden" name="qd" value="Regexp-Grammars">
        <input type="hidden" name="source" value="metacpan">
        <input type="search" name="q" placeholder="grep distribution" class="form-control tool-bar-form">
        <input type="submit" style="display: none">
     </form>
    </li>
    <li class="version-jump">
<select onchange="document.location.href=&#39;/release/&#39;+this.value+&#39;/view/lib/Regexp/Grammars.pm&#39;" class="form-control tool-bar-form">
  <option disabled selected>Jump to version</option>
<option
  disabled
  value="DCONWAY/Regexp-Grammars-1.058"
>1.058
  (DCONWAY on 2022-09-15)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.057"
>1.057
  (DCONWAY on 2020-05-22)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.056"
>1.056
  (DCONWAY on 2020-05-22)</option>
<optgroup label="BackPAN">'
<option
  
  value="DCONWAY/Regexp-Grammars-1.055"
>1.055
  (DCONWAY on 2020-05-07)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.054"
>1.054
  (DCONWAY on 2020-05-05)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.053"
>1.053
  (DCONWAY on 2020-05-03)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.052"
>1.052
  (DCONWAY on 2019-07-16)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.051"
>1.051
  (DCONWAY on 2019-07-02)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.050"
>1.050
  (DCONWAY on 2019-04-26)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.049"
>1.049
  (DCONWAY on 2018-10-04)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.048"
>1.048
  (DCONWAY on 2017-09-26)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.047"
>1.047
  (DCONWAY on 2017-09-26)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.045"
>1.045
  (DCONWAY on 2016-01-12)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.044"
>1.044
  (DCONWAY on 2015-12-15)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.043"
>1.043
  (DCONWAY on 2015-12-14)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.042"
>1.042
  (DCONWAY on 2015-09-16)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.041"
>1.041
  (DCONWAY on 2015-05-03)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.040"
>1.040
  (DCONWAY on 2015-03-26)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.039"
>1.039
  (DCONWAY on 2015-02-06)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.038"
>1.038
  (DCONWAY on 2014-12-11)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.036"
>1.036
  (DCONWAY on 2014-09-15)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.035"
>1.035
  (DCONWAY on 2014-06-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.034"
>1.034
  (DCONWAY on 2014-06-10)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.033"
>1.033
  (DCONWAY on 2013-08-31)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.032"
>1.032
  (DCONWAY on 2013-08-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.031"
>1.031
  (DCONWAY on 2013-08-18)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.030"
>1.030
  (DCONWAY on 2013-06-25)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.029"
>1.029
  (DCONWAY on 2013-06-25)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.028"
>1.028
  (DCONWAY on 2013-05-10)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.027"
>1.027
  (DCONWAY on 2013-05-09)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.026"
>1.026
  (DCONWAY on 2013-01-30)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.025"
>1.025
  (DCONWAY on 2013-01-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.021"
>1.021
  (DCONWAY on 2012-08-20)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.020"
>1.020
  (DCONWAY on 2012-08-16)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.016"
>1.016
  (DCONWAY on 2012-03-09)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.015"
>1.015
  (DCONWAY on 2012-02-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.014"
>1.014
  (DCONWAY on 2011-11-02)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.013"
>1.013
  (DCONWAY on 2011-06-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.012"
>1.012
  (DCONWAY on 2010-11-03)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.011"
>1.011
  (DCONWAY on 2010-10-11)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.010"
>1.010
  (DCONWAY on 2010-09-27)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.009"
>1.009
  (DCONWAY on 2010-09-18)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.008"
>1.008
  (DCONWAY on 2010-09-17)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.005"
>1.005
  (DCONWAY on 2010-06-22)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.002"
>1.002
  (DCONWAY on 2009-12-08)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.001005"
>1.001005
  (DCONWAY on 2009-08-02)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.001004"
>1.001004
  (DCONWAY on 2009-07-24)</option>
</optgroup>
</select>
    </li>
    <li class="version-diff">
<select onchange="document.location.href='/release/DCONWAY/Regexp-Grammars-1.058/diff/' + encodeURIComponent(this.value) + '/lib/Regexp/Grammars.pm'
" class="form-control tool-bar-form">
  <option disabled selected>Diff with version</option>
<option
  disabled
  value="DCONWAY/Regexp-Grammars-1.058"
>1.058
  (DCONWAY on 2022-09-15)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.057"
>1.057
  (DCONWAY on 2020-05-22)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.056"
>1.056
  (DCONWAY on 2020-05-22)</option>
<optgroup label="BackPAN">'
<option
  
  value="DCONWAY/Regexp-Grammars-1.055"
>1.055
  (DCONWAY on 2020-05-07)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.054"
>1.054
  (DCONWAY on 2020-05-05)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.053"
>1.053
  (DCONWAY on 2020-05-03)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.052"
>1.052
  (DCONWAY on 2019-07-16)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.051"
>1.051
  (DCONWAY on 2019-07-02)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.050"
>1.050
  (DCONWAY on 2019-04-26)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.049"
>1.049
  (DCONWAY on 2018-10-04)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.048"
>1.048
  (DCONWAY on 2017-09-26)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.047"
>1.047
  (DCONWAY on 2017-09-26)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.045"
>1.045
  (DCONWAY on 2016-01-12)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.044"
>1.044
  (DCONWAY on 2015-12-15)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.043"
>1.043
  (DCONWAY on 2015-12-14)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.042"
>1.042
  (DCONWAY on 2015-09-16)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.041"
>1.041
  (DCONWAY on 2015-05-03)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.040"
>1.040
  (DCONWAY on 2015-03-26)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.039"
>1.039
  (DCONWAY on 2015-02-06)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.038"
>1.038
  (DCONWAY on 2014-12-11)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.036"
>1.036
  (DCONWAY on 2014-09-15)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.035"
>1.035
  (DCONWAY on 2014-06-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.034"
>1.034
  (DCONWAY on 2014-06-10)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.033"
>1.033
  (DCONWAY on 2013-08-31)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.032"
>1.032
  (DCONWAY on 2013-08-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.031"
>1.031
  (DCONWAY on 2013-08-18)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.030"
>1.030
  (DCONWAY on 2013-06-25)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.029"
>1.029
  (DCONWAY on 2013-06-25)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.028"
>1.028
  (DCONWAY on 2013-05-10)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.027"
>1.027
  (DCONWAY on 2013-05-09)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.026"
>1.026
  (DCONWAY on 2013-01-30)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.025"
>1.025
  (DCONWAY on 2013-01-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.021"
>1.021
  (DCONWAY on 2012-08-20)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.020"
>1.020
  (DCONWAY on 2012-08-16)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.016"
>1.016
  (DCONWAY on 2012-03-09)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.015"
>1.015
  (DCONWAY on 2012-02-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.014"
>1.014
  (DCONWAY on 2011-11-02)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.013"
>1.013
  (DCONWAY on 2011-06-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.012"
>1.012
  (DCONWAY on 2010-11-03)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.011"
>1.011
  (DCONWAY on 2010-10-11)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.010"
>1.010
  (DCONWAY on 2010-09-27)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.009"
>1.009
  (DCONWAY on 2010-09-18)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.008"
>1.008
  (DCONWAY on 2010-09-17)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.005"
>1.005
  (DCONWAY on 2010-06-22)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.002"
>1.002
  (DCONWAY on 2009-12-08)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.001005"
>1.001005
  (DCONWAY on 2009-08-02)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.001004"
>1.001004
  (DCONWAY on 2009-07-24)</option>
</optgroup>
</select>
    </li>

    <li>
<ul class="dependencies">
  <li class="nav-header">Dependencies</li>
  <li><a href="https://metacpan.org/pod/Test::More" title="Test::More" class="ellipsis">Test::More</a></li>
  <li><a href="https://metacpan.org/pod/version" title="version" class="ellipsis">version</a></li>
  <li><i class="ttip" title="dynamic_config enabled">and possibly others</i></li>
  <li>
    <hr>
  </li>
  <li>
    <a href="https://metacpan.org/module/Regexp::Grammars/requires">Reverse dependencies</a>
  </li>
  <li>
    <a href="http://deps.cpantesters.org/?module=Regexp%3A%3AGrammars">CPAN Testers List</a>
  </li>
  <li>
    <a href="https://cpandeps.grinnz.com/?dist=Regexp-Grammars">Dependency graph</a>
  </li>
</ul>
    </li>
    <li class="nav-header">Permalinks</li>
    <li>
      <a href="https://metacpan.org/release/DCONWAY/Regexp-Grammars-1.058/view/lib/Regexp/Grammars.pm">This version</a>
    </li>
    <li>
      <a href="./Regexp::Grammars.html">Latest version</a>
    </li>
    <li>
<div class="plussers">
<div class="nav-header">++ed by:</div>
<div>
<a class="display-all" href="https://metacpan.org/author/KARJALA"><img src="https://www.gravatar.com/avatar/9685932c4be47d9e6370f49230700c40?d=identicon&amp;s=20" title="KARJALA" alt="KARJALA"></a>
<a class="display-all" href="https://metacpan.org/author/DBOEHMER"><img src="https://www.gravatar.com/avatar/220fbe10dba79664fe84771d5ea32763?d=identicon&amp;s=20" title="DBOEHMER" alt="DBOEHMER"></a>
<a class="display-all" href="https://metacpan.org/author/FRACTAL"><img src="https://www.gravatar.com/avatar/4f4ebf9a8b36a6d1905586ed479e693e?d=identicon&amp;s=20" title="FRACTAL" alt="FRACTAL"></a>
<a class="display-all" href="https://metacpan.org/author/TOBYINK"><img src="https://www.gravatar.com/avatar/f8faf2a422aecd1007b7d54c19ce7f39?d=identicon&amp;s=20" title="TOBYINK" alt="TOBYINK"></a>
<a class="display-all" href="https://metacpan.org/author/HANENKAMP"><img src="https://www.gravatar.com/avatar/e5b51c69496e22e3e2d037604cc6d8c9?d=identicon&amp;s=20" title="HANENKAMP" alt="HANENKAMP"></a>
</div>
<!-- Display counts of plussers-->
<div>
    <a href="https://metacpan.org/dist/Regexp-Grammars/plussers">19 PAUSE users</a>
</div>
<div>
    19 non-PAUSE users
</div>
</div>
    </li>
    <li>
<div id="metacpan_contributors">
  <div>
    <button class="btn-link"
      onclick="$(this).hide(); $('#metacpan_contributors ul').slideDown(); return false;"
    >and 1 contributors</button>
  </div>
  <ul style="display: none">
    <li class="contributor"
      data-contrib-email="DCONWAY@CPAN.org"
    >
      <img class="gravatar" width="20" height="20" src="https://www.gravatar.com/avatar/d41d8cd98f00b204e9800998ecf8427e?d=identicon&amp;s=20" />
      Damian Conway
    </li>
  </ul>
</div>
    </li>
              </ul>
            </div>
          </nav>
          <div class="content-navigation">
<div class="breadcrumbs">
  <span>
    <a data-keyboard-shortcut="g a" rel="author" href="https://metacpan.org/author/DCONWAY" class="author-name">Damian Conway</a>
  </span>
  <span>&nbsp;/&nbsp;</span>
  <div class="release dist-release status-latest maturity-released">
    <span class="dropdown"><b class="caret"></b></span>
<select onchange="document.location.href=&#39;/release/&#39;+this.value+&#39;/view/lib/Regexp/Grammars.pm&#39;" class="">
<option
  selected
  value="DCONWAY/Regexp-Grammars-1.058"
>1.058
  (DCONWAY on 2022-09-15)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.057"
>1.057
  (DCONWAY on 2020-05-22)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.056"
>1.056
  (DCONWAY on 2020-05-22)</option>
<optgroup label="BackPAN">'
<option
  
  value="DCONWAY/Regexp-Grammars-1.055"
>1.055
  (DCONWAY on 2020-05-07)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.054"
>1.054
  (DCONWAY on 2020-05-05)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.053"
>1.053
  (DCONWAY on 2020-05-03)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.052"
>1.052
  (DCONWAY on 2019-07-16)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.051"
>1.051
  (DCONWAY on 2019-07-02)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.050"
>1.050
  (DCONWAY on 2019-04-26)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.049"
>1.049
  (DCONWAY on 2018-10-04)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.048"
>1.048
  (DCONWAY on 2017-09-26)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.047"
>1.047
  (DCONWAY on 2017-09-26)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.045"
>1.045
  (DCONWAY on 2016-01-12)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.044"
>1.044
  (DCONWAY on 2015-12-15)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.043"
>1.043
  (DCONWAY on 2015-12-14)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.042"
>1.042
  (DCONWAY on 2015-09-16)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.041"
>1.041
  (DCONWAY on 2015-05-03)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.040"
>1.040
  (DCONWAY on 2015-03-26)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.039"
>1.039
  (DCONWAY on 2015-02-06)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.038"
>1.038
  (DCONWAY on 2014-12-11)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.036"
>1.036
  (DCONWAY on 2014-09-15)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.035"
>1.035
  (DCONWAY on 2014-06-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.034"
>1.034
  (DCONWAY on 2014-06-10)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.033"
>1.033
  (DCONWAY on 2013-08-31)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.032"
>1.032
  (DCONWAY on 2013-08-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.031"
>1.031
  (DCONWAY on 2013-08-18)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.030"
>1.030
  (DCONWAY on 2013-06-25)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.029"
>1.029
  (DCONWAY on 2013-06-25)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.028"
>1.028
  (DCONWAY on 2013-05-10)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.027"
>1.027
  (DCONWAY on 2013-05-09)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.026"
>1.026
  (DCONWAY on 2013-01-30)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.025"
>1.025
  (DCONWAY on 2013-01-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.021"
>1.021
  (DCONWAY on 2012-08-20)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.020"
>1.020
  (DCONWAY on 2012-08-16)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.016"
>1.016
  (DCONWAY on 2012-03-09)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.015"
>1.015
  (DCONWAY on 2012-02-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.014"
>1.014
  (DCONWAY on 2011-11-02)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.013"
>1.013
  (DCONWAY on 2011-06-29)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.012"
>1.012
  (DCONWAY on 2010-11-03)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.011"
>1.011
  (DCONWAY on 2010-10-11)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.010"
>1.010
  (DCONWAY on 2010-09-27)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.009"
>1.009
  (DCONWAY on 2010-09-18)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.008"
>1.008
  (DCONWAY on 2010-09-17)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.005"
>1.005
  (DCONWAY on 2010-06-22)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.002"
>1.002
  (DCONWAY on 2009-12-08)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.001005"
>1.001005
  (DCONWAY on 2009-08-02)</option>
<option
  
  value="DCONWAY/Regexp-Grammars-1.001004"
>1.001004
  (DCONWAY on 2009-07-24)</option>
</optgroup>
</select>
    <a data-keyboard-shortcut="g d" class="release-name" href="https://metacpan.org/dist/Regexp-Grammars">Regexp-Grammars-1.058</a>
  </div>
<span class="river-gauge-gauge">
  <svg width="24px"
       height="15px"
       version="1.1"
       xmlns="http://www.w3.org/2000/svg"
       xmlns:xlink="http://www.w3.org/1999/xlink">

    <g>
      <title>        River stage three &#10;
          • 19 direct dependents &#10;          • 631 total dependents
      </title>

      <rect x="0"  y="0" width="4" height="15" fill="#7ea3f2" />
      <rect x="5"  y="0" width="4" height="15" fill="#7ea3f2" />
      <rect x="10"  y="0" width="4" height="15" fill="#7ea3f2" />
      <rect x="15"  y="0" width="4" height="15" fill="#e4e2e2" />
      <rect x="20"  y="0" width="4" height="15" fill="#e4e2e2" />
    </g>
  </svg>

</span>
<div id="Regexp-Grammars-fav" class="logged_in">
<form action="https://metacpan.org/account/favorite/add" style="display: inline" onsubmit="return favDistribution(this)">
    <input type="hidden" name="remove" value="0">
    <input type="hidden" name="release" value="Regexp-Grammars-1.058">
    <input type="hidden" name="author" value="DCONWAY">
    <input type="hidden" name="distribution" value="Regexp-Grammars">
    <button type="submit" class="favorite highlight"><span>38</span> ++</button>
</form>
</div>
<div class="logged_out">
<a href="./Regexp::Grammars.html" onclick="alert('Please sign in to add favorites'); return false" class="favorite highlight">
<span>38</span> ++</a>
</div>
   / <span>Regexp::Grammars</span>
</div>
          </div>
          <main class="content">


<nav class="toc">
  <div class="toc-header"><strong>Contents</strong></div>
<ul>
  <li><a href="./Regexp::Grammars.html#NAME">NAME</a></li>
  <li><a href="./Regexp::Grammars.html#VERSION">VERSION</a></li>
  <li><a href="./Regexp::Grammars.html#SYNOPSIS">SYNOPSIS</a></li>
  <li><a href="./Regexp::Grammars.html#QUICKSTART-CHEATSHEET">QUICKSTART CHEATSHEET</a>
    <ul>
      <li><a href="./Regexp::Grammars.html#In-your-program...">In your program...</a></li>
      <li><a href="./Regexp::Grammars.html#Defining-and-using-named-grammars...">Defining and using named grammars...</a></li>
      <li><a href="./Regexp::Grammars.html#Defining-rules-in-your-grammar...">Defining rules in your grammar...</a></li>
      <li><a href="./Regexp::Grammars.html#Matching-rules-in-your-grammar...">Matching rules in your grammar...</a></li>
      <li><a href="./Regexp::Grammars.html#In-your-grammar&#39;s-code-blocks...">In your grammar&#39;s code blocks...</a></li>
      <li><a href="./Regexp::Grammars.html#Directives...">Directives...</a></li>
    </ul>
  </li>
  <li><a href="./Regexp::Grammars.html#DESCRIPTION">DESCRIPTION</a>
    <ul>
      <li><a href="./Regexp::Grammars.html#Setting-up-the-module">Setting up the module</a></li>
      <li><a href="./Regexp::Grammars.html#Structure-of-a-Regexp::Grammars-grammar">Structure of a Regexp::Grammars grammar</a></li>
      <li><a href="./Regexp::Grammars.html#Tokens-vs-rules-(whitespace-handling)">Tokens vs rules (whitespace handling)</a>
        <ul>
          <li><a href="./Regexp::Grammars.html#Per-rule-whitespace-handling">Per-rule whitespace handling</a></li>
        </ul>
      </li>
      <li><a href="./Regexp::Grammars.html#Calling-subrules">Calling subrules</a></li>
      <li><a href="./Regexp::Grammars.html#Subrule-results">Subrule results</a>
        <ul>
          <li><a href="./Regexp::Grammars.html#Turning-off-the-context-substring">Turning off the context substring</a></li>
        </ul>
      </li>
      <li><a href="./Regexp::Grammars.html#Renaming-subrule-results">Renaming subrule results</a></li>
      <li><a href="./Regexp::Grammars.html#List-like-subrule-calls">List-like subrule calls</a></li>
      <li><a href="./Regexp::Grammars.html#Parametric-subrules">Parametric subrules</a>
        <ul>
          <li><a href="./Regexp::Grammars.html#Accessing-subrule-arguments-more-cleanly">Accessing subrule arguments more cleanly</a></li>
        </ul>
      </li>
      <li><a href="./Regexp::Grammars.html#Pseudo-subrules">Pseudo-subrules</a></li>
      <li><a href="./Regexp::Grammars.html#Aliased-literals">Aliased literals</a></li>
      <li><a href="./Regexp::Grammars.html#Amnesiac-subrule-calls">Amnesiac subrule calls</a></li>
      <li><a href="./Regexp::Grammars.html#Private-subrule-calls">Private subrule calls</a></li>
      <li><a href="./Regexp::Grammars.html#Lookahead-(zero-width)-subrules">Lookahead (zero-width) subrules</a></li>
      <li><a href="./Regexp::Grammars.html#Matching-separated-lists">Matching separated lists</a>
        <ul>
          <li><a href="./Regexp::Grammars.html#Matching-separated-lists-with-a-trailing-separator">Matching separated lists with a trailing separator</a></li>
        </ul>
      </li>
      <li><a href="./Regexp::Grammars.html#Matching-hash-keys">Matching hash keys</a></li>
      <li><a href="./Regexp::Grammars.html#Rematching-subrule-results">Rematching subrule results</a></li>
      <li><a href="./Regexp::Grammars.html#Rematching-balanced-delimiters">Rematching balanced delimiters</a></li>
      <li><a href="./Regexp::Grammars.html#Rematching-parametric-results-and-delimiters">Rematching parametric results and delimiters</a></li>
      <li><a href="./Regexp::Grammars.html#Tracking-and-reporting-match-positions">Tracking and reporting match positions</a></li>
    </ul>
  </li>
  <li><a href="./Regexp::Grammars.html#Autoactions">Autoactions</a></li>
  <li><a href="./Regexp::Grammars.html#Named-grammars">Named grammars</a>
    <ul>
      <li><a href="./Regexp::Grammars.html#Defining-a-named-grammar">Defining a named grammar</a></li>
      <li><a href="./Regexp::Grammars.html#Using-a-named-grammar">Using a named grammar</a></li>
      <li><a href="./Regexp::Grammars.html#Overriding-an-inherited-rule-or-token">Overriding an inherited rule or token</a></li>
      <li><a href="./Regexp::Grammars.html#Augmenting-an-inherited-rule-or-token">Augmenting an inherited rule or token</a></li>
      <li><a href="./Regexp::Grammars.html#Debugging-named-grammars">Debugging named grammars</a></li>
    </ul>
  </li>
  <li><a href="./Regexp::Grammars.html#Common-parsing-techniques">Common parsing techniques</a>
    <ul>
      <li><a href="./Regexp::Grammars.html#Result-distillation">Result distillation</a>
        <ul>
          <li><a href="./Regexp::Grammars.html#List-result-distillation">List result distillation</a></li>
          <li><a href="./Regexp::Grammars.html#Manual-result-distillation">Manual result distillation</a></li>
          <li><a href="./Regexp::Grammars.html#Programmatic-result-distillation">Programmatic result distillation</a></li>
        </ul>
      </li>
      <li><a href="./Regexp::Grammars.html#Parse-time-data-processing">Parse-time data processing</a></li>
      <li><a href="./Regexp::Grammars.html#Object-oriented-parsing">Object-oriented parsing</a>
        <ul>
          <li>
            <ul>
              <li><a href="./Regexp::Grammars.html#An-important-caveat-regarding-OO-rules">An important caveat regarding OO rules</a></li>
            </ul>
          </li>
          <li><a href="./Regexp::Grammars.html#A-naming-shortcut">A naming shortcut</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="./Regexp::Grammars.html#Debugging1">Debugging</a>
    <ul>
      <li><a href="./Regexp::Grammars.html#Debugging-grammar-creation-with-%3Clogfile:...%3E">Debugging grammar creation with &lt;logfile:...&gt;</a></li>
      <li><a href="./Regexp::Grammars.html#Debugging-grammar-execution-with-%3Cdebug:...%3E">Debugging grammar execution with &lt;debug:...&gt;</a>
        <ul>
          <li><a href="./Regexp::Grammars.html#Resizing-the-context-string">Resizing the context string</a></li>
        </ul>
      </li>
      <li><a href="./Regexp::Grammars.html#User-defined-logging-with-%3Clog:...%3E">User-defined logging with &lt;log:...&gt;</a></li>
      <li><a href="./Regexp::Grammars.html#Debugging-non-grammars">Debugging non-grammars</a></li>
    </ul>
  </li>
  <li><a href="./Regexp::Grammars.html#Handling-errors-when-parsing">Handling errors when parsing</a>
    <ul>
      <li><a href="./Regexp::Grammars.html#Requirements">Requirements</a></li>
      <li><a href="./Regexp::Grammars.html#Handling-failure">Handling failure</a>
        <ul>
          <li><a href="./Regexp::Grammars.html#Error-messages">Error messages</a></li>
          <li><a href="./Regexp::Grammars.html#Warning-messages">Warning messages</a></li>
          <li><a href="./Regexp::Grammars.html#Stubbing">Stubbing</a></li>
          <li><a href="./Regexp::Grammars.html#Localizing-the-(semi-)automatic-error-messages">Localizing the (semi-)automatic error messages</a></li>
        </ul>
      </li>
      <li><a href="./Regexp::Grammars.html#Restricting-how-long-a-parse-runs">Restricting how long a parse runs</a>
        <ul>
          <li><a href="./Regexp::Grammars.html#Immediate-timeouts">Immediate timeouts</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="./Regexp::Grammars.html#Scoping-considerations">Scoping considerations</a></li>
  <li><a href="./Regexp::Grammars.html#INTERFACE">INTERFACE</a>
    <ul>
      <li><a href="./Regexp::Grammars.html#Perl-API">Perl API</a></li>
      <li><a href="./Regexp::Grammars.html#Grammar-syntax">Grammar syntax</a>
        <ul>
          <li><a href="./Regexp::Grammars.html#Directives1">Directives</a></li>
          <li><a href="./Regexp::Grammars.html#Subrule-calls">Subrule calls</a></li>
        </ul>
      </li>
      <li><a href="./Regexp::Grammars.html#Special-variables-within-grammar-actions">Special variables within grammar actions</a></li>
    </ul>
  </li>
  <li><a href="./Regexp::Grammars.html#IMPORTANT-CONSTRAINTS-AND-LIMITATIONS">IMPORTANT CONSTRAINTS AND LIMITATIONS</a></li>
  <li><a href="./Regexp::Grammars.html#DIAGNOSTICS">DIAGNOSTICS</a></li>
  <li><a href="./Regexp::Grammars.html#CONFIGURATION-AND-ENVIRONMENT">CONFIGURATION AND ENVIRONMENT</a></li>
  <li><a href="./Regexp::Grammars.html#DEPENDENCIES">DEPENDENCIES</a></li>
  <li><a href="./Regexp::Grammars.html#INCOMPATIBILITIES">INCOMPATIBILITIES</a></li>
  <li><a href="./Regexp::Grammars.html#BUGS">BUGS</a></li>
  <li><a href="./Regexp::Grammars.html#CONTRIBUTING">CONTRIBUTING</a></li>
  <li><a href="./Regexp::Grammars.html#AUTHOR">AUTHOR</a></li>
  <li><a href="./Regexp::Grammars.html#LICENCE-AND-COPYRIGHT">LICENCE AND COPYRIGHT</a></li>
  <li><a href="./Regexp::Grammars.html#DISCLAIMER-OF-WARRANTY">DISCLAIMER OF WARRANTY</a></li>
</ul></nav>
<div class="pod anchors">
<h1 id="NAME">NAME</h1>

<p>Regexp::Grammars - Add grammatical parsing features to Perl 5.10 regexes</p>

<h1 id="VERSION">VERSION</h1>

<p>This document describes Regexp::Grammars version 1.058</p>

<h1 id="SYNOPSIS">SYNOPSIS</h1>

<pre><code>    use Regexp::Grammars;

    my $parser = qr{
        (?:
            &lt;Verb&gt;               # Parse and save a Verb in a scalar
            &lt;.ws&gt;                # Parse but don&#39;t save whitespace
            &lt;Noun&gt;               # Parse and save a Noun in a scalar

            &lt;type=(?{ rand &gt; 0.5 ? &#39;VN&#39; : &#39;VerbNoun&#39; })&gt;
                                 # Save result of expression in a scalar
        |
            (?:
                &lt;[Noun]&gt;         # Parse a Noun and save result in a list
                                     (saved under the key &#39;Noun&#39;)
                &lt;[PostNoun=ws]&gt;  # Parse whitespace, save it in a list
                                 #   (saved under the key &#39;PostNoun&#39;)
            )+

            &lt;Verb&gt;               # Parse a Verb and save result in a scalar
                                     (saved under the key &#39;Verb&#39;)

            &lt;type=(?{ &#39;VN&#39; })&gt;   # Save a literal in a scalar
        |
            &lt;debug: match&gt;       # Turn on the integrated debugger here
            &lt;.Cmd= (?: mv? )&gt;    # Parse but don&#39;t capture a subpattern
                                     (name it &#39;Cmd&#39; for debugging purposes)
            &lt;[File]&gt;+            # Parse 1+ Files and save them in a list
                                     (saved under the key &#39;File&#39;)
            &lt;debug: off&gt;         # Turn off the integrated debugger here
            &lt;Dest=File&gt;          # Parse a File and save it in a scalar
                                     (saved under the key &#39;Dest&#39;)
        )

        ################################################################

        &lt;token: File&gt;              # Define a subrule named File
            &lt;.ws&gt;                  #  - Parse but don&#39;t capture whitespace
            &lt;MATCH= ([\w-]+) &gt;     #  - Parse the subpattern and capture
                                   #    matched text as the result of the
                                   #    subrule

        &lt;token: Noun&gt;              # Define a subrule named Noun
            cat | dog | fish       #  - Match an alternative (as usual)

        &lt;rule: Verb&gt;               # Define a whitespace-sensitive subrule
            eats                   #  - Match a literal (after any space)
            &lt;Object=Noun&gt;?         #  - Parse optional subrule Noun and
                                   #    save result under the key &#39;Object&#39;
        |                          #  Or else...
            &lt;AUX&gt;                  #  - Parse subrule AUX and save result
            &lt;part= (eaten|seen) &gt;  #  - Match a literal, save under &#39;part&#39;

        &lt;token: AUX&gt;               # Define a whitespace-insensitive subrule
            (has | is)             #  - Match an alternative and capture
            (?{ $MATCH = uc $^N }) #  - Use captured text as subrule result

    }x;

    # Match the grammar against some text...
    if ($text =~ $parser) {
        # If successful, the hash %/ will have the hierarchy of results...
        process_data_in( %/ );
    }</code></pre>

<h1 id="QUICKSTART-CHEATSHEET"><a id="QUICKSTART"></a>QUICKSTART CHEATSHEET</h1>

<h2 id="In-your-program..."><a id="In"></a><a id="In-your-program"></a>In your program...</h2>

<pre><code>    use Regexp::Grammars;    Allow enhanced regexes in lexical scope
    %/                       Result-hash for successful grammar match</code></pre>

<h2 id="Defining-and-using-named-grammars..."><a id="Defining"></a><a id="Defining-and-using-named-grammars"></a>Defining and using named grammars...</h2>

<pre><code>    &lt;grammar:  GRAMMARNAME&gt;  Define a named grammar that can be inherited
    &lt;extends:  GRAMMARNAME&gt;  Current grammar inherits named grammar&#39;s rules</code></pre>

<h2 id="Defining-rules-in-your-grammar..."><a id="Defining1"></a><a id="Defining-rules-in-your-grammar"></a>Defining rules in your grammar...</h2>

<pre><code>    &lt;rule:     RULENAME&gt;     Define rule with magic whitespace
    &lt;token:    RULENAME&gt;     Define rule without magic whitespace

    &lt;objrule:  CLASS= NAME&gt;  Define rule that blesses return-hash into class
    &lt;objtoken: CLASS= NAME&gt;  Define token that blesses return-hash into class

    &lt;objrule:  CLASS&gt;        Shortcut for above (rule name derived from class)
    &lt;objtoken: CLASS&gt;        Shortcut for above (token name derived from class)</code></pre>

<h2 id="Matching-rules-in-your-grammar..."><a id="Matching"></a><a id="Matching-rules-in-your-grammar"></a>Matching rules in your grammar...</h2>

<pre><code>    &lt;RULENAME&gt;                Call named subrule (may be fully qualified)
                              save result to $MATCH{RULENAME}

    &lt;RULENAME(...)&gt;           Call named subrule, passing args to it

    &lt;!RULENAME&gt;               Call subrule and fail if it matches
    &lt;!RULENAME(...)&gt;          (shorthand for (?!&lt;.RULENAME&gt;) )

    &lt;:IDENT&gt;                  Match contents of $ARG{IDENT} as a pattern
    &lt;\:IDENT&gt;                 Match contents of $ARG{IDENT} as a literal
    &lt;/:IDENT&gt;                 Match closing delimiter for $ARG{IDENT}

    &lt;%HASH&gt;                   Match longest possible key of hash
    &lt;%HASH {PAT}&gt;             Match any key of hash that also matches PAT

    &lt;/IDENT&gt;                  Match closing delimiter for $MATCH{IDENT}
    &lt;\_IDENT&gt;                 Match the literal contents of $MATCH{IDENT}

    &lt;ALIAS= RULENAME&gt;         Call subrule, save result in $MATCH{ALIAS}
    &lt;ALIAS= %HASH&gt;            Match a hash key, save key in $MATCH{ALIAS}
    &lt;ALIAS= ( PATTERN )&gt;      Match pattern, save match in $MATCH{ALIAS}
    &lt;ALIAS= (?{ CODE })&gt;      Execute code, save value in $MATCH{ALIAS}
    &lt;ALIAS= &#39;STR&#39; &gt;           Save specified string in $MATCH{ALIAS}
    &lt;ALIAS= 42 &gt;              Save specified number in $MATCH{ALIAS}
    &lt;ALIAS= /IDENT&gt;           Match closing delim, save as $MATCH{ALIAS}
    &lt;ALIAS= \_IDENT&gt;          Match &#39;$MATCH{IDENT}&#39;, save as $MATCH{ALIAS}

    &lt;.SUBRULE&gt;                Call subrule (one of the above forms),
                              but don&#39;t save the result in %MATCH


    &lt;[SUBRULE]&gt;               Call subrule (one of the above forms), but
                              append result instead of overwriting it

    &lt;SUBRULE1&gt;+ % &lt;SUBRULE2&gt;  Match one or more repetitions of SUBRULE1
                              as long as they&#39;re separated by SUBRULE2
    &lt;SUBRULE1&gt; ** &lt;SUBRULE2&gt;  Same (only for backwards compatibility)

    &lt;SUBRULE1&gt;* % &lt;SUBRULE2&gt;  Match zero or more repetitions of SUBRULE1
                              as long as they&#39;re separated by SUBRULE2

    &lt;SUBRULE1&gt;* %% &lt;SUBRULE2&gt; Match zero or more repetitions of SUBRULE1
                              as long as they&#39;re separated by SUBRULE2
                              and allow an optional trailing SUBRULE2</code></pre>

<h2 id="In-your-grammar&#39;s-code-blocks..."><a id="In1"></a><a id="In-your-grammar-s-code-blocks"></a>In your grammar&#39;s code blocks...</h2>

<pre><code>    $CAPTURE    Alias for $^N (the most recent paren capture)
    $CONTEXT    Another alias for $^N
    $INDEX      Current index of next matching position in string
    %MATCH      Current rule&#39;s result-hash
    $MATCH      Magic override value (returned instead of result-hash)
    %ARG        Current rule&#39;s argument hash
    $DEBUG      Current match-time debugging mode</code></pre>

<h2 id="Directives..."><a id="Directives"></a>Directives...</h2>

<pre><code>    &lt;require: (?{ CODE })   &gt;  Fail if code evaluates false
    &lt;timeout: INT           &gt;  Fail after specified number of seconds
    &lt;debug:   COMMAND       &gt;  Change match-time debugging mode
    &lt;logfile: LOGFILE       &gt;  Change debugging log file (default: STDERR)
    &lt;fatal:   TEXT|(?{CODE})&gt;  Queue error message and fail parse
    &lt;error:   TEXT|(?{CODE})&gt;  Queue error message and backtrack
    &lt;warning: TEXT|(?{CODE})&gt;  Queue warning message and continue
    &lt;log:     TEXT|(?{CODE})&gt;  Explicitly add a message to debugging log
    &lt;ws:      PATTERN       &gt;  Override automatic whitespace matching
    &lt;minimize:&gt;                Simplify the result of a subrule match
    &lt;context:&gt;                 Switch on context substring retention
    &lt;nocontext:&gt;               Switch off context substring retention</code></pre>

<h1 id="DESCRIPTION">DESCRIPTION</h1>

<p>This module adds a small number of new regex constructs that can be used within Perl 5.10 patterns to implement complete recursive-descent parsing.</p>

<p>Perl 5.10 already supports recursive-descent <i>matching</i>, via the new <code>(?&lt;name&gt;...)</code> and <code>(?&amp;name)</code> constructs. For example, here is a simple matcher for a subset of the LaTeX markup language:</p>

<pre><code>    $matcher = qr{
        (?&amp;File)

        (?(DEFINE)
            (?&lt;File&gt;     (?&amp;Element)* )

            (?&lt;Element&gt;  \s* (?&amp;Command)
                      |  \s* (?&amp;Literal)
            )

            (?&lt;Command&gt;  \\ \s* (?&amp;Literal) \s* (?&amp;Options)? \s* (?&amp;Args)? )

            (?&lt;Options&gt;  \[ \s* (?:(?&amp;Option) (?:\s*,\s* (?&amp;Option) )*)? \s* \])

            (?&lt;Args&gt;     \{ \s* (?&amp;Element)* \s* \}  )

            (?&lt;Option&gt;   \s* [^][\$&amp;%#_{}~^\s,]+     )

            (?&lt;Literal&gt;  \s* [^][\$&amp;%#_{}~^\s]+      )
        )
    }xms</code></pre>

<p>This technique makes it possible to use regexes to recognize complex, hierarchical--and even recursive--textual structures. The problem is that Perl 5.10 doesn&#39;t provide any support for extracting that hierarchical data into nested data structures. In other words, using Perl 5.10 you can <i>match</i> complex data, but not <i>parse</i> it into an internally useful form.</p>

<p>An additional problem when using Perl 5.10 regexes to match complex data formats is that you have to make sure you remember to insert whitespace-matching constructs (such as <code>\s*</code>) at every possible position where the data might contain ignorable whitespace. This reduces the readability of such patterns, and increases the chance of errors (typically caused by overlooking a location where whitespace might appear).</p>

<p>The Regexp::Grammars module solves both those problems.</p>

<p>If you import the module into a particular lexical scope, it preprocesses any regex in that scope, so as to implement a number of extensions to the standard Perl 5.10 regex syntax. These extensions simplify the task of defining and calling subrules within a grammar, and allow those subrule calls to capture and retain the components of they match in a proper hierarchical manner.</p>

<p>For example, the above LaTeX matcher could be converted to a full LaTeX parser (and considerably tidied up at the same time), like so:</p>

<pre><code>    use Regexp::Grammars;
    $parser = qr{
        &lt;File&gt;

        &lt;rule: File&gt;       &lt;[Element]&gt;*

        &lt;rule: Element&gt;    &lt;Command&gt; | &lt;Literal&gt;

        &lt;rule: Command&gt;    \\  &lt;Literal&gt;  &lt;Options&gt;?  &lt;Args&gt;?

        &lt;rule: Options&gt;    \[  &lt;[Option]&gt;+ % (,)  \]

        &lt;rule: Args&gt;       \{  &lt;[Element]&gt;*  \}

        &lt;rule: Option&gt;     [^][\$&amp;%#_{}~^\s,]+

        &lt;rule: Literal&gt;    [^][\$&amp;%#_{}~^\s]+
    }xms</code></pre>

<p>Note that there is no need to explicitly place <code>\s*</code> subpatterns throughout the rules; that is taken care of automatically.</p>

<p>If the Regexp::Grammars version of this regex were successfully matched against some appropriate LaTeX document, each rule would call the subrules specified within it, and then return a hash containing whatever result each of those subrules returned, with each result indexed by the subrule&#39;s name.</p>

<p>That is, if the rule named <code>Command</code> were invoked, it would first try to match a backslash, then it would call the three subrules <code>&lt;Literal&gt;</code>, <code>&lt;Options&gt;</code>, and <code>&lt;Args&gt;</code> (in that sequence). If they all matched successfully, the <code>Command</code> rule would then return a hash with three keys: <code>&#39;Literal&#39;</code>, <code>&#39;Options&#39;</code>, and <code>&#39;Args&#39;</code>. The value for each of those hash entries would be whatever result-hash the subrules themselves had returned when matched.</p>

<p>In this way, each level of the hierarchical regex can generate hashes recording everything its own subrules matched, so when the entire pattern matches, it produces a tree of nested hashes that represent the structured data the pattern matched.</p>

<p>For example, if the previous regex grammar were matched against a string containing:</p>

<pre><code>    \documentclass[a4paper,11pt]{article}
    \author{D. Conway}</code></pre>

<p>it would automatically extract a data structure equivalent to the following (but with several extra &quot;empty&quot; keys, which are described in <a href="./Regexp::Grammars.html#Subrule-results">&quot;Subrule results&quot;</a>):</p>

<pre><code>    {
        &#39;file&#39; =&gt; {
            &#39;element&#39; =&gt; [
                {
                    &#39;command&#39; =&gt; {
                        &#39;literal&#39; =&gt; &#39;documentclass&#39;,
                        &#39;options&#39; =&gt; {
                            &#39;option&#39;  =&gt; [ &#39;a4paper&#39;, &#39;11pt&#39; ],
                        },
                        &#39;args&#39;    =&gt; {
                            &#39;element&#39; =&gt; [ &#39;article&#39; ],
                        }
                    }
                },
                {
                    &#39;command&#39; =&gt; {
                        &#39;literal&#39; =&gt; &#39;author&#39;,
                        &#39;args&#39; =&gt; {
                            &#39;element&#39; =&gt; [
                                {
                                    &#39;literal&#39; =&gt; &#39;D.&#39;,
                                },
                                {
                                    &#39;literal&#39; =&gt; &#39;Conway&#39;,
                                }
                            ]
                        }
                    }
                }
            ]
        }
    }</code></pre>

<p>The data structure that Regexp::Grammars produces from a regex match is available to the surrounding program in the magic variable <code>%/</code>.</p>

<p>Regexp::Grammars provides many features that simplify the extraction of hierarchical data via a regex match, and also some features that can simplify the processing of that data once it has been extracted. The following sections explain each of those features, and some of the parsing techniques they support.</p>

<h2 id="Setting-up-the-module"><a id="Setting"></a>Setting up the module</h2>

<p>Just add:</p>

<pre><code>    use Regexp::Grammars;</code></pre>

<p>to any lexical scope. Any regexes within that scope will automatically now implement the new parsing constructs:</p>

<pre><code>    use Regexp::Grammars;

    my $parser = qr/ regex with $extra &lt;chocolatey&gt; grammar bits /;</code></pre>

<p>Note that you do not to use the <code>/x</code> modifier when declaring a regex grammar (though you certainly may). But even if you don&#39;t, the module quietly adds a <code>/x</code> to every regex within the scope of its usage. Otherwise, the default <i>&quot;a whitespace character matches exactly that whitespace character&quot;</i> behaviour of Perl regexes would mess up your grammar&#39;s parsing. If you need the non-<code>/x</code> behaviour, you can still use the <code>(?-x)</code> of <code>(?-x:...)</code> directives to switch off <code>/x</code> within one or more of your grammar&#39;s components.</p>

<p>Once the grammar has been processed, you can then match text against the extended regexes, in the usual manner (i.e. via a <code>=~</code> match):</p>

<pre><code>    if ($input_text =~ $parser) {
        ...
    }</code></pre>

<p>After a successful match, the variable <code>%/</code> will contain a series of nested hashes representing the structured hierarchical data captured during the parse.</p>

<h2 id="Structure-of-a-Regexp::Grammars-grammar"><a id="Structure"></a>Structure of a Regexp::Grammars grammar</h2>

<p>A Regexp::Grammars specification consists of a <i>start-pattern</i> (which may include both standard Perl 5.10 regex syntax, as well as special Regexp::Grammars directives), followed by one or more rule or token definitions.</p>

<p>For example:</p>

<pre><code>    use Regexp::Grammars;
    my $balanced_brackets = qr{

        # Start-pattern...
        &lt;paren_pair&gt; | &lt;brace_pair&gt;

        # Rule definition...
        &lt;rule: paren_pair&gt;
            \(  (?: &lt;escape&gt; | &lt;paren_pair&gt; | &lt;brace_pair&gt; | [^()] )*  \)

        # Rule definition...
        &lt;rule: brace_pair&gt;
            \{  (?: &lt;escape&gt; | &lt;paren_pair&gt; | &lt;brace_pair&gt; | [^{}] )*  \}

        # Token definition...
        &lt;token: escape&gt;
            \\ .
    }xms;</code></pre>

<p>The start-pattern at the beginning of the grammar acts like the &quot;top&quot; token of the grammar, and must be matched completely for the grammar to match.</p>

<p>This pattern is treated like a token for whitespace matching behaviour (see <a href="./Regexp::Grammars.html#Tokens-vs-rules-(whitespace-handling)">&quot;Tokens vs rules (whitespace handling)&quot;</a>). That is, whitespace in the start-pattern is treated like whitespace in any normal Perl regex.</p>

<p>The rules and tokens are declarations only and they are not directly matched. Instead, they act like subroutines, and are invoked by name from the initial pattern (or from within a rule or token).</p>

<p>Each rule or token extends from the directive that introduces it up to either the next rule or token directive, or (in the case of the final rule or token) to the end of the grammar.</p>

<h2 id="Tokens-vs-rules-(whitespace-handling)"><a id="Tokens"></a><a id="Tokens-vs-rules--whitespace-handling"></a>Tokens vs rules (whitespace handling)</h2>

<p>The difference between a token and a rule is that a token treats any whitespace within it exactly as a normal Perl regular expression would. That is, a sequence of whitespace in a token is ignored if the <code>/x</code> modifier is in effect, or else matches the same literal sequence of whitespace characters (if <code>/x</code> is not in effect).</p>

<p>In a rule, most sequences of whitespace are treated as matching the implicit subrule <code>&lt;.ws&gt;</code>, which is automatically predefined to match optional whitespace (i.e. <code>\s*</code>).</p>

<p>Exceptions to this behaviour are whitespaces before a <code>|</code> or a code block or an explicit space-matcher (such as <code>&lt;ws&gt;</code> or <code>\s</code>), or at the very end of the rule)</p>

<p>In other words, a rule such as:</p>

<pre><code>    &lt;rule: sentence&gt;   &lt;noun&gt; &lt;verb&gt;
                   |   &lt;verb&gt; &lt;noun&gt;</code></pre>

<p>is equivalent to a token with added non-capturing whitespace matching:</p>

<pre><code>    &lt;token: sentence&gt;  &lt;.ws&gt; &lt;noun&gt; &lt;.ws&gt; &lt;verb&gt;
                    |  &lt;.ws&gt; &lt;verb&gt; &lt;.ws&gt; &lt;noun&gt;</code></pre>

<p>You can explicitly define a <code>&lt;ws&gt;</code> token to change that default behaviour. For example, you could alter the definition of &quot;whitespace&quot; to include Perlish comments, by adding an explicit <code>&lt;token: ws&gt;</code>:</p>

<pre><code>    &lt;token: ws&gt;
        (?: \s+ | #[^\n]* )*</code></pre>

<p>But be careful not to define <code>&lt;ws&gt;</code> as a rule, as this will lead to all kinds of infinitely recursive unpleasantness.</p>

<h3 id="Per-rule-whitespace-handling"><a id="Per"></a>Per-rule whitespace handling</h3>

<p>Redefining the <code>&lt;ws&gt;</code> token changes its behaviour throughout the entire grammar, within every rule definition. Usually that&#39;s appropriate, but sometimes you need finer-grained control over whitespace handling.</p>

<p>So Regexp::Grammars provides the <code>&lt;ws:&gt;</code> directive, which allows you to override the implicit whitespace-matches-whitespace behaviour only within the current rule.</p>

<p>Note that this directive does <i>not</i> redefine <code>&lt;ws&gt;</code> within the rule; it simply specifies what to replace each whitespace sequence with (instead of replacing each with a <code>&lt;ws&gt;</code> call).</p>

<p>For example, if a language allows one kind of comment between statements and another within statements, you could parse it with:</p>

<pre><code>    &lt;rule: program&gt;
        # One type of comment between...
        &lt;ws: (\s++ | \# .*? \n)* &gt;

        # ...colon-separated statements...
        &lt;[statement]&gt;+ % ( ; )


    &lt;rule: statement&gt;
        # Another type of comment...
        &lt;ws: (\s*+ | \#{ .*? }\# )* &gt;

        # ...between comma-separated commands...
        &lt;cmd&gt;  &lt;[arg]&gt;+ % ( , )</code></pre>

<p>Note that each directive only applies to the rule in which it is specified. In every other rule in the grammar, whitespace would still match the usual <code>&lt;ws&gt;</code> subrule.</p>

<h2 id="Calling-subrules"><a id="Calling"></a>Calling subrules</h2>

<p>To invoke a rule to match at any point, just enclose the rule&#39;s name in angle brackets (like in Perl 6). There must be no space between the opening bracket and the rulename. For example::</p>

<pre><code>    qr{
        file:             # Match literal sequence &#39;f&#39; &#39;i&#39; &#39;l&#39; &#39;e&#39; &#39;:&#39;
        &lt;name&gt;            # Call &lt;rule: name&gt;
        &lt;options&gt;?        # Call &lt;rule: options&gt; (it&#39;s okay if it fails)

        &lt;rule: name&gt;
            # etc.
    }x;</code></pre>

<p>If you need to match a literal pattern that would otherwise look like a subrule call, just backslash-escape the leading angle:</p>

<pre><code>    qr{
        file:             # Match literal sequence &#39;f&#39; &#39;i&#39; &#39;l&#39; &#39;e&#39; &#39;:&#39;
        \&lt;name&gt;           # Match literal sequence &#39;&lt;&#39; &#39;n&#39; &#39;a&#39; &#39;m&#39; &#39;e&#39; &#39;&gt;&#39;
        &lt;options&gt;?        # Call &lt;rule: options&gt; (it&#39;s okay if it fails)

        &lt;rule: name&gt;
            # etc.
    }x;</code></pre>

<h2 id="Subrule-results"><a id="Subrule"></a>Subrule results</h2>

<p>If a subrule call successfully matches, the result of that match is a reference to a hash. That hash reference is stored in the current rule&#39;s own result-hash, under the name of the subrule that was invoked. The hash will, in turn, contain the results of any more deeply nested subrule calls, each stored under the name by which the nested subrule was invoked.</p>

<p>In other words, if the rule <code>sentence</code> is defined:</p>

<pre><code>    &lt;rule: sentence&gt;
        &lt;noun&gt; &lt;verb&gt; &lt;object&gt;</code></pre>

<p>then successfully calling the rule:</p>

<pre><code>    &lt;sentence&gt;</code></pre>

<p>causes a new hash entry at the current nesting level. That entry&#39;s key will be <code>&#39;sentence&#39;</code> and its value will be a reference to a hash, which in turn will have keys: <code>&#39;noun&#39;</code>, <code>&#39;verb&#39;</code>, and <code>&#39;object&#39;</code>.</p>

<p>In addition each result-hash has one extra key: the empty string. The value for this key is whatever substring the entire subrule call matched. This value is known as the <i>context substring</i>.</p>

<p>So, for example, a successful call to <code>&lt;sentence&gt;</code> might add something like the following to the current result-hash:</p>

<pre><code>    sentence =&gt; {
        &quot;&quot;     =&gt; &#39;I saw a dog&#39;,
        noun   =&gt; &#39;I&#39;,
        verb   =&gt; &#39;saw&#39;,
        object =&gt; {
            &quot;&quot;      =&gt; &#39;a dog&#39;,
            article =&gt; &#39;a&#39;,
            noun    =&gt; &#39;dog&#39;,
        },
    }</code></pre>

<p>Note, however, that if the result-hash at any level contains <i>only</i> the empty-string key (i.e. the subrule did not call any sub-subrules or save any of their nested result-hashes), then the hash is &quot;unpacked&quot; and just the context substring itself is returned.</p>

<p>For example, if <code>&lt;rule: sentence&gt;</code> had been defined:</p>

<pre><code>    &lt;rule: sentence&gt;
        I see dead people</code></pre>

<p>then a successful call to the rule would only add:</p>

<pre><code>    sentence =&gt; &#39;I see dead people&#39;</code></pre>

<p>to the current result-hash.</p>

<p>This is a useful feature because it prevents a series of nested subrule calls from producing very unwieldy data structures. For example, without this automatic unpacking, even the simple earlier example:</p>

<pre><code>    &lt;rule: sentence&gt;
        &lt;noun&gt; &lt;verb&gt; &lt;object&gt;</code></pre>

<p>would produce something needlessly complex, such as:</p>

<pre><code>    sentence =&gt; {
        &quot;&quot;     =&gt; &#39;I saw a dog&#39;,
        noun   =&gt; {
            &quot;&quot; =&gt; &#39;I&#39;,
        },
        verb   =&gt; {
            &quot;&quot; =&gt; &#39;saw&#39;,
        },
        object =&gt; {
            &quot;&quot;      =&gt; &#39;a dog&#39;,
            article =&gt; {
                &quot;&quot; =&gt; &#39;a&#39;,
            },
            noun    =&gt; {
                &quot;&quot; =&gt; &#39;dog&#39;,
            },
        },
    }</code></pre>

<h3 id="Turning-off-the-context-substring"><a id="Turning"></a>Turning off the context substring</h3>

<p>The context substring is convenient for debugging and for generating error messages but, in a large grammar, or when parsing a long string, the capture and storage of many nested substrings may quickly become prohibitively expensive.</p>

<p>So Regexp::Grammars provides a directive to prevent context substrings from being retained. Any rule or token that includes the directive <code>&lt;nocontext:&gt;</code> anywhere in the rule&#39;s body will not retain any context substring it matches...unless that substring would be the only entry in its result hash (which only happens within objrules and objtokens).</p>

<p>If a <code>&lt;nocontext:&gt;</code> directive appears <i>before</i> the first rule or token definition (i.e. as part of the main pattern), then the entire grammar will discard all context substrings from every one of its rules and tokens.</p>

<p>However, you can override this universal prohibition with a second directive: <code>&lt;context:&gt;</code>. If this directive appears in any rule or token, that rule or token <i>will</i> save its context substring, even if a global <code>&lt;nocontext:&gt;</code> is in effect.</p>

<p>This means that this grammar:</p>

<pre><code>    qr{
        &lt;Command&gt;

        &lt;rule: Command&gt;
            &lt;nocontext:&gt;
            &lt;Keyword&gt; &lt;arg=(\S+)&gt;+ % &lt;.ws&gt;

        &lt;token: Keyword&gt;
            &lt;Move&gt; | &lt;Copy&gt; | &lt;Delete&gt;

        # etc.
    }x</code></pre>

<p>and this grammar:</p>

<pre><code>    qr{
        &lt;nocontext:&gt;
        &lt;Command&gt;

        &lt;rule: Command&gt;
            &lt;Keyword&gt; &lt;arg=(\S+)&gt;+ % &lt;.ws&gt;

        &lt;token: Keyword&gt;
            &lt;context:&gt;
            &lt;Move&gt; | &lt;Copy&gt; | &lt;Delete&gt;

        # etc.
    }x</code></pre>

<p>will behave identically (saving context substrings for keywords, but not for commands), except that the first version will also retain the global context substring (i.e. $/{&quot;&quot;}), whereas the second version will not.</p>

<p>Note that <code>&lt;context:&gt;</code> and <code>&lt;nocontext:&gt;</code> have no effect on, or even any interaction with, the various <a href="./Regexp::Grammars.html#Result-distillation">result distillation</a> mechanisms, which continue to work in the usual way when either or both of the directives is used.</p>

<h2 id="Renaming-subrule-results"><a id="Renaming"></a>Renaming subrule results</h2>

<p>It is not always convenient to have subrule results stored under the same name as the rule itself. Rule names should be optimized for understanding the behaviour of the parser, whereas result names should be optimized for understanding the structure of the data. Often those two goals are identical, but not always; sometimes rule names need to describe what the data looks like, while result names need to describe what the data means.</p>

<p>For example, sometimes you need to call the same rule twice, to match two syntactically identical components whose positions give then semantically distinct meanings:</p>

<pre><code>    &lt;rule: copy_cmd&gt;
        copy &lt;file&gt; &lt;file&gt;</code></pre>

<p>The problem here is that, if the second call to <code>&lt;file&gt;</code> succeeds, its result-hash will be stored under the key <code>&#39;file&#39;</code>, clobbering the data that was returned from the first call to <code>&lt;file&gt;</code>.</p>

<p>To avoid such problems, Regexp::Grammars allows you to <i>alias</i> any subrule call, so that it is still invoked by the original name, but its result-hash is stored under a different key. The syntax for that is: <code>&lt;<i>alias</i>=<i>rulename</i>&gt;</code>. For example:</p>

<pre><code>    &lt;rule: copy_cmd&gt;
        copy &lt;from=file&gt; &lt;to=file&gt;</code></pre>

<p>Here, <code>&lt;rule: file&gt;</code> is called twice, with the first result-hash being stored under the key <code>&#39;from&#39;</code>, and the second result-hash being stored under the key <code>&#39;to&#39;</code>.</p>

<p>Note, however, that the alias before the <code>=</code> must be a proper identifier (i.e. a letter or underscore, followed by letters, digits, and/or underscores). Aliases that start with an underscore and aliases named <code>MATCH</code> have special meaning (see <a href="./Regexp::Grammars.html#Private-subrule-calls">&quot;Private subrule calls&quot;</a> and <a href="./Regexp::Grammars.html#Result-distillation">&quot;Result distillation&quot;</a> respectively).</p>

<p>Aliases can also be useful for normalizing data that may appear in different formats and sequences. For example:</p>

<pre><code>    &lt;rule: copy_cmd&gt;
        copy &lt;from=file&gt;        &lt;to=file&gt;
      | dup    &lt;to=file&gt;  as  &lt;from=file&gt;
      |      &lt;from=file&gt;  -&gt;    &lt;to=file&gt;
      |        &lt;to=file&gt;  &lt;-  &lt;from=file&gt;</code></pre>

<p>Here, regardless of which order the old and new files are specified, the result-hash always gets:</p>

<pre><code>    copy_cmd =&gt; {
        from =&gt; &#39;oldfile&#39;,
          to =&gt; &#39;newfile&#39;,
    }</code></pre>

<h2 id="List-like-subrule-calls"><a id="List"></a>List-like subrule calls</h2>

<p>If a subrule call is quantified with a repetition specifier:</p>

<pre><code>    &lt;rule: file_sequence&gt;
        &lt;file&gt;+</code></pre>

<p>then each repeated match overwrites the corresponding entry in the surrounding rule&#39;s result-hash, so only the result of the final repetition will be retained. That is, if the above example matched the string <code><span style="white-space: nowrap;">&quot;foo.pl bar.py baz.php&quot;</span></code>, then the result-hash would contain:</p>

<pre><code>    file_sequence {
        &quot;&quot;   =&gt; &#39;foo.pl bar.py baz.php&#39;,
        file =&gt; &#39;baz.php&#39;,
    }</code></pre>

<p>Usually, that&#39;s not the desired outcome, so Regexp::Grammars provides another mechanism by which to call a subrule; one that saves <i>all</i> repetitions of its results.</p>

<p>A regular subrule call consists of the rule&#39;s name surrounded by angle brackets. If, instead, you surround the rule&#39;s name with <code>&lt;[...]&gt;</code> (angle <i>and</i> square brackets) like so:</p>

<pre><code>    &lt;rule: file_sequence&gt;
        &lt;[file]&gt;+</code></pre>

<p>then the rule is invoked in exactly the same way, but the result of that submatch is pushed onto an array nested inside the appropriate result-hash entry. In other words, if the above example matched the same <code><span style="white-space: nowrap;">&quot;foo.pl bar.py baz.php&quot;</span></code> string, the result-hash would contain:</p>

<pre><code>    file_sequence {
        &quot;&quot;   =&gt; &#39;foo.pl bar.py baz.php&#39;,
        file =&gt; [ &#39;foo.pl&#39;, &#39;bar.py&#39;, &#39;baz.php&#39; ],
    }</code></pre>

<p>This &quot;listifying subrule call&quot; can also be useful for non-repeated subrule calls, if the same subrule is invoked in several places in a grammar. For example if a cmdline option could be given either one or two values, you might parse it:</p>

<pre><code>    &lt;rule: size_option&gt;
        -size &lt;[size]&gt; (?: x &lt;[size]&gt; )?</code></pre>

<p>The result-hash entry for <code>&#39;size&#39;</code> would then always contain an array, with either one or two elements, depending on the input being parsed.</p>

<p>Listifying subrules can also be given <a href="./Regexp::Grammars.html#Renaming-subrule-results">aliases</a>, just like ordinary subrules. The alias is always specified inside the square brackets:</p>

<pre><code>    &lt;rule: size_option&gt;
        -size &lt;[size=pos_integer]&gt; (?: x &lt;[size=pos_integer]&gt; )?</code></pre>

<p>Here, the sizes are parsed using the <code>pos_integer</code> rule, but saved in the result-hash in an array under the key <code>&#39;size&#39;</code>.</p>

<h2 id="Parametric-subrules"><a id="Parametric"></a>Parametric subrules</h2>

<p>When a subrule is invoked, it can be passed a set of named arguments (specified as <i>key</i><code>=&gt;</code><i>values</i> pairs). This argument list is placed in a normal Perl regex code block and must appear immediately after the subrule name, before the closing angle bracket.</p>

<p>Within the subrule that has been invoked, the arguments can be accessed via the special hash <code>%ARG</code>. For example:</p>

<pre><code>    &lt;rule: block&gt;
        &lt;tag&gt;
            &lt;[block]&gt;*
        &lt;end_tag(?{ tag=&gt;$MATCH{tag} })&gt;  # ...call subrule with argument

    &lt;token: end_tag&gt;
        end_ (??{ quotemeta $ARG{tag} })</code></pre>

<p>Here the <code>block</code> rule first matches a <code>&lt;tag&gt;</code>, and the corresponding substring is saved in <code>$MATCH{tag}</code>. It then matches any number of nested blocks. Finally it invokes the <code>&lt;end_tag&gt;</code> subrule, passing it an argument whose name is <code>&#39;tag&#39;</code> and whose value is the current value of <code>$MATCH{tag}</code> (i.e. the original opening tag).</p>

<p>When it is thus invoked, the <code>end_tag</code> token first matches <code>&#39;end_&#39;</code>, then interpolates the literal value of the <code>&#39;tag&#39;</code> argument and attempts to match it.</p>

<p>Any number of named arguments can be passed when a subrule is invoked. For example, we could generalize the <code>end_tag</code> rule to allow any prefix (not just <code>&#39;end_&#39;</code>), and also to allow for &#39;if...fi&#39;-style reversed tags, like so:</p>

<pre><code>    &lt;rule: block&gt;
        &lt;tag&gt;
            &lt;[block]&gt;*
        &lt;end_tag (?{ prefix=&gt;&#39;end&#39;, tag=&gt;$MATCH{tag} })&gt;

    &lt;token: end_tag&gt;
        (??{ $ARG{prefix} // q{(?!)} })      # ...prefix as pattern
        (??{ quotemeta $ARG{tag} })          # ...tag as literal
      |
        (??{ quotemeta reverse $ARG{tag} })  # ...reversed tag</code></pre>

<p>Note that, if you do not need to interpolate values (such as <code>$MATCH{tag}</code>) into a subrule&#39;s argument list, you can use simple parentheses instead of <code>(?{...})</code>, like so:</p>

<pre><code>        &lt;end_tag( prefix=&gt;&#39;end&#39;, tag=&gt;&#39;head&#39; )&gt;</code></pre>

<p>The only types of values you can use in this simplified syntax are numbers and single-quote-delimited strings. For anything more complex, put the argument list in a full <code>(?{...})</code>.</p>

<p>As the earlier examples show, the single most common type of argument is one of the form: <i>IDENTIFIER</i> <code>=&gt; $MATCH{</code><i>IDENTIFIER</i><code>}</code>. That is, it&#39;s a common requirement to pass an element of <code>%MATCH</code> into a subrule, named with its own key.</p>

<p>Because this is such a common usage, Regexp::Grammars provides a shortcut. If you use simple parentheses (instead of <code>(?{...})</code> parentheses) then instead of a pair, you can specify an argument using a colon followed by an identifier. This argument is replaced by a named argument whose name is the identifier and whose value is the corresponding item from <code>%MATCH</code>. So, for example, instead of:</p>

<pre><code>        &lt;end_tag(?{ prefix=&gt;&#39;end&#39;, tag=&gt;$MATCH{tag} })&gt;</code></pre>

<p>you can just write:</p>

<pre><code>        &lt;end_tag( prefix=&gt;&#39;end&#39;, :tag )&gt;</code></pre>

<p>Note that, from Perl 5.20 onwards, due to changes in the way that Perl parses regexes, Regexp::Grammars does not support explicitly passing elements of <code>%MATCH</code> as argument values within a list subrule (yeah, it&#39;s a very specific and obscure edge-case):</p>

<pre><code>        &lt;[end_tag(?{ prefix=&gt;&#39;end&#39;, tag=&gt;$MATCH{tag} })]&gt;   # Does not work</code></pre>

<p>Note, however, that the shortcut:</p>

<pre><code>        &lt;[end_tag( prefix=&gt;&#39;end&#39;, :tag )]&gt;</code></pre>

<p>still works correctly.</p>

<h3 id="Accessing-subrule-arguments-more-cleanly"><a id="Accessing"></a>Accessing subrule arguments more cleanly</h3>

<p>As the preceding examples illustrate, using subrule arguments effectively generally requires the use of run-time interpolated subpatterns via the <code>(??{...})</code> construct.</p>

<p>This produces ugly rule bodies such as:</p>

<pre><code>    &lt;token: end_tag&gt;
        (??{ $ARG{prefix} // q{(?!)} })      # ...prefix as pattern
        (??{ quotemeta $ARG{tag} })          # ...tag as literal
      |
        (??{ quotemeta reverse $ARG{tag} })  # ...reversed tag</code></pre>

<p>To simplify these common usages, Regexp::Grammars provides three convenience constructs.</p>

<p>A subrule call of the form <code>&lt;:</code><i>identifier</i><code>&gt;</code> is equivalent to:</p>

<pre><code>    (??{ $ARG{&#39;identifier&#39;} // q{(?!)} })</code></pre>

<p>Namely: <i>&quot;Match the contents of <code>$ARG{&#39;identifier&#39;}</code>, treating those contents as a pattern.&quot;</i></p>

<p>A subrule call of the form <code>&lt;\:</code><i>identifier</i><code>&gt;</code> (that is: a <a href="./Regexp::Grammars.html#Rematching-subrule-results">matchref</a> with a colon after the backslash) is equivalent to:</p>

<pre><code>    (??{ defined $ARG{&#39;identifier&#39;}
            ? quotemeta($ARG{&#39;identifier&#39;})
            : &#39;(?!)&#39;
    })</code></pre>

<p>Namely: <i>&quot;Match the contents of <code>$ARG{&#39;identifier&#39;}</code>, treating those contents as a literal.&quot;</i></p>

<p>A subrule call of the form <code>&lt;/:</code><i>identifier</i><code>&gt;</code> (that is: an <a href="./Regexp::Grammars.html#Rematching-balanced-delimiters">invertref</a> with a colon after the forward slash) is equivalent to:</p>

<pre><code>    (??{ defined $ARG{&#39;identifier&#39;}
            ? quotemeta(reverse $ARG{&#39;identifier&#39;})
            : &#39;(?!)&#39;
    })</code></pre>

<p>Namely: <i>&quot;Match the closing delimiter corresponding to the contents of <code>$ARG{&#39;identifier&#39;}</code>, as if it were a literal&quot;</i>.</p>

<p>The availability of these three constructs mean that we could rewrite the above <code>&lt;end_tag&gt;</code> token much more cleanly as:</p>

<pre><code>    &lt;token: end_tag&gt;
        &lt;:prefix&gt;      # ...prefix as pattern
        &lt;\:tag&gt;        # ...tag as a literal
      |
        &lt;/:tag&gt;        # ...reversed tag</code></pre>

<p>In general these constructs mean that, within a subrule, if you want to match an argument passed to that subrule, you use <code>&lt;:</code><i>ARGNAME</i><code>&gt;</code> (to match the argument as a pattern) or <code>&lt;\:</code><i>ARGNAME</i><code>&gt;</code> (to match the argument as a literal).</p>

<p>Note the consistent mnemonic in these various subrule-like interpolations of named arguments: the name is always prefixed by a colon.</p>

<p>In other words, the <code>&lt;:ARGNAME&gt;</code> form works just like a <code>&lt;RULENAME&gt;</code>, except that the leading colon tells Regexp::Grammars to use the contents of <code>$ARG{&#39;ARGNAME&#39;}</code> as the subpattern, instead of the contents of <code>(?&amp;RULENAME)</code></p>

<p>Likewise, the <code>&lt;\:ARGNAME&gt;</code> and <code>&lt;/:ARGNAME&gt;</code> constructs work exactly like <code>&lt;\_MATCHNAME&gt;</code> and <code>&lt;/INVERTNAME&gt;</code> respectively, except that the leading colon indicates that the matchref or invertref should be taken from <code>%ARG</code> instead of from <code>%MATCH</code>.</p>

<h2 id="Pseudo-subrules"><a id="Pseudo"></a>Pseudo-subrules</h2>

<p>Aliases can also be given to standard Perl subpatterns, as well as to code blocks within a regex. The syntax for subpatterns is:</p>

<pre><code>    &lt;ALIAS= (SUBPATTERN) &gt;</code></pre>

<p>In other words, the syntax is exactly like an aliased subrule call, except that the rule name is replaced with a set of parentheses containing the subpattern. Any parentheses--capturing or non-capturing--will do.</p>

<p>The effect of aliasing a standard subpattern is to cause whatever that subpattern matches to be saved in the result-hash, using the alias as its key. For example:</p>

<pre><code>    &lt;rule: file_command&gt;

        &lt;cmd=(mv|cp|ln)&gt;  &lt;from=file&gt;  &lt;to=file&gt;</code></pre>

<p>Here, the <code>&lt;cmd=(mv|cp|ln)&gt;</code> is treated exactly like a regular <code>(mv|cp|ln)</code>, but whatever substring it matches is saved in the result-hash under the key <code>&#39;cmd&#39;</code>.</p>

<p>The syntax for aliasing code blocks is:</p>

<pre><code>    &lt;ALIAS= (?{ your($code-&gt;here) }) &gt;</code></pre>

<p>Note, however, that the code block must be specified in the standard Perl 5.10 regex notation: <code>(?{...})</code>. A common mistake is to write:</p>

<pre><code>    &lt;ALIAS= { your($code-&gt;here } &gt;</code></pre>

<p>instead, which will attempt to interpolate <code>$code</code> before the regex is even compiled, as such variables are only &quot;protected&quot; from interpolation inside a <code>(?{...})</code>.</p>

<p>When correctly specified, this construct executes the code in the block and saves the result of that execution in the result-hash, using the alias as its key. Aliased code blocks are useful for adding semantic information based on which branch of a rule is executed. For example, consider the <code>copy_cmd</code> alternatives shown earlier:</p>

<pre><code>    &lt;rule: copy_cmd&gt;
        copy &lt;from=file&gt;        &lt;to=file&gt;
      | dup    &lt;to=file&gt;  as  &lt;from=file&gt;
      |      &lt;from=file&gt;  -&gt;    &lt;to=file&gt;
      |        &lt;to=file&gt;  &lt;-  &lt;from=file&gt;</code></pre>

<p>Using aliased code blocks, you could add an extra field to the result- hash to describe which form of the command was detected, like so:</p>

<pre><code>    &lt;rule: copy_cmd&gt;
        copy &lt;from=file&gt;        &lt;to=file&gt;  &lt;type=(?{ &#39;std&#39; })&gt;
      | dup    &lt;to=file&gt;  as  &lt;from=file&gt;  &lt;type=(?{ &#39;rev&#39; })&gt;
      |      &lt;from=file&gt;  -&gt;    &lt;to=file&gt;  &lt;type=(?{  +1   })&gt;
      |        &lt;to=file&gt;  &lt;-  &lt;from=file&gt;  &lt;type=(?{  -1   })&gt;</code></pre>

<p>Now, if the rule matched, the result-hash would contain something like:</p>

<pre><code>    copy_cmd =&gt; {
        from =&gt; &#39;oldfile&#39;,
          to =&gt; &#39;newfile&#39;,
        type =&gt; &#39;fwd&#39;,
    }</code></pre>

<p>Note that, in addition to the semantics described above, aliased subpatterns and code blocks also become visible to Regexp::Grammars&#39; integrated debugger (see <a href="https://metacpan.org/pod/Debugging">Debugging</a>).</p>

<h2 id="Aliased-literals"><a id="Aliased"></a>Aliased literals</h2>

<p>As the previous example illustrates, it is inconveniently verbose to assign constants via aliased code blocks. So Regexp::Grammars provides a short-cut. It is possible to directly alias a numeric literal or a single-quote delimited literal string, without putting either inside a code block. For example, the previous example could also be written:</p>

<pre><code>    &lt;rule: copy_cmd&gt;
        copy &lt;from=file&gt;        &lt;to=file&gt;  &lt;type=&#39;std&#39;&gt;
      | dup    &lt;to=file&gt;  as  &lt;from=file&gt;  &lt;type=&#39;rev&#39;&gt;
      |      &lt;from=file&gt;  -&gt;    &lt;to=file&gt;  &lt;type= +1  &gt;
      |        &lt;to=file&gt;  &lt;-  &lt;from=file&gt;  &lt;type= -1  &gt;</code></pre>

<p>Note that only these two forms of literal are supported in this abbreviated syntax.</p>

<h2 id="Amnesiac-subrule-calls"><a id="Amnesiac"></a>Amnesiac subrule calls</h2>

<p>By default, every subrule call saves its result into the result-hash, either under its own name, or under an alias.</p>

<p>However, sometimes you may want to refactor some literal part of a rule into one or more subrules, without having those submatches added to the result-hash. The syntax for calling a subrule, but ignoring its return value is:</p>

<pre><code>    &lt;.SUBRULE&gt;</code></pre>

<p>(which is stolen directly from Perl 6).</p>

<p>For example, you may prefer to rewrite a rule such as:</p>

<pre><code>    &lt;rule: paren_pair&gt;

        \(
            (?: &lt;escape&gt; | &lt;paren_pair&gt; | &lt;brace_pair&gt; | [^()] )*
        \)</code></pre>

<p>without any literal matching, like so:</p>

<pre><code>    &lt;rule: paren_pair&gt;

        &lt;.left_paren&gt;
            (?: &lt;escape&gt; | &lt;paren_pair&gt; | &lt;brace_pair&gt; | &lt;.non_paren&gt; )*
        &lt;.right_paren&gt;

    &lt;token: left_paren&gt;   \(
    &lt;token: right_paren&gt;  \)
    &lt;token: non_paren&gt;    [^()]</code></pre>

<p>Moreover, as the individual components inside the parentheses probably aren&#39;t being captured for any useful purpose either, you could further optimize that to:</p>

<pre><code>    &lt;rule: paren_pair&gt;

        &lt;.left_paren&gt;
            (?: &lt;.escape&gt; | &lt;.paren_pair&gt; | &lt;.brace_pair&gt; | &lt;.non_paren&gt; )*
        &lt;.right_paren&gt;</code></pre>

<p>Note that you can also use the dot modifier on an aliased subpattern:</p>

<pre><code>    &lt;.Alias= (SUBPATTERN) &gt;</code></pre>

<p>This seemingly contradictory behaviour (of giving a subpattern a name, then deliberately ignoring that name) actually does make sense in one situation. Providing the alias makes the subpattern visible to the debugger, while using the dot stops it from affecting the result-hash. See <a href="./Regexp::Grammars.html#Debugging-non-grammars">&quot;Debugging non-grammars&quot;</a> for an example of this usage.</p>

<h2 id="Private-subrule-calls"><a id="Private"></a>Private subrule calls</h2>

<p>If a rule name (or an alias) begins with an underscore:</p>

<pre><code>     &lt;_RULENAME&gt;       &lt;_ALIAS=RULENAME&gt;
    &lt;[_RULENAME]&gt;     &lt;[_ALIAS=RULENAME]&gt;</code></pre>

<p>then matching proceeds as normal, and any result that is returned is stored in the current result-hash in the usual way.</p>

<p>However, when any rule finishes (and just before it returns) it first filters its result-hash, removing any entries whose keys begin with an underscore. This means that any subrule with an underscored name (or with an underscored alias) remembers its result, but only until the end of the current rule. Its results are effectively private to the current rule.</p>

<p>This is especially useful in conjunction with <a href="./Regexp::Grammars.html#Result-distillation">result distillation</a>.</p>

<h2 id="Lookahead-(zero-width)-subrules"><a id="Lookahead"></a><a id="Lookahead--zero-width--subrules"></a>Lookahead (zero-width) subrules</h2>

<p>Non-capturing subrule calls can be used in normal lookaheads:</p>

<pre><code>    &lt;rule: qualified_typename&gt;
        # A valid typename and has a :: in it...
        (?= &lt;.typename&gt; )  [^\s:]+ :: \S+

    &lt;rule: identifier&gt;
        # An alpha followed by alnums (but not a valid typename)...
        (?! &lt;.typename&gt; )    [^\W\d]\w*</code></pre>

<p>but the syntax is a little unwieldy. More importantly, an internal problem with backtracking causes positive lookaheads to mess up the module&#39;s named capturing mechanism.</p>

<p>So Regexp::Grammars provides two shorthands:</p>

<pre><code>    &lt;!typename&gt;        same as: (?! &lt;.typename&gt; )
    &lt;?typename&gt;        same as: (?= &lt;.typename&gt; ) ...but works correctly!</code></pre>

<p>These two constructs can also be called with arguments, if necessary:</p>

<pre><code>    &lt;rule: Command&gt;
        &lt;Keyword&gt;
        (?:
            &lt;!Terminator(:Keyword)&gt;  &lt;Args=(\S+)&gt;
        )?
        &lt;Terminator(:Keyword)&gt;</code></pre>

<p>Note that, as the above equivalences imply, neither of these forms of a subroutine call ever captures what it matches.</p>

<h2 id="Matching-separated-lists"><a id="Matching1"></a>Matching separated lists</h2>

<p>One of the commonest tasks in text parsing is to match a list of unspecified length, in which items are separated by a fixed token. Things like:</p>

<pre><code>    1, 2, 3 , 4 ,13, 91        # Numbers separated by commas and spaces

    g-c-a-g-t-t-a-c-a          # DNA bases separated by dashes

    /usr/local/bin             # Names separated by directory markers

    /usr:/usr/local:bin        # Directories separated by colons</code></pre>

<p>The usual construct required to parse these kinds of structures is either:</p>

<pre><code>    &lt;rule: list&gt;

        &lt;item&gt; &lt;separator&gt; &lt;list&gt;     # recursive definition
      | &lt;item&gt;                        # base case</code></pre>

<p>or, if you want to allow zero-or-more items instead of requiring one-or-more:</p>

<pre><code>    &lt;rule: list_opt&gt;
        &lt;list&gt;?                       # entire list may be missing

    &lt;rule: list&gt;                      # as before...
        &lt;item&gt; &lt;separator&gt; &lt;list&gt;     #   recursive definition
      | &lt;item&gt;                        #   base case</code></pre>

<p>Or, more efficiently, but less prettily:</p>

<pre><code>    &lt;rule: list&gt;
        &lt;[item]&gt; (?: &lt;separator&gt; &lt;[item]&gt; )*           # one-or-more

    &lt;rule: list_opt&gt;
        (?: &lt;[item]&gt; (?: &lt;separator&gt; &lt;[item]&gt; )* )?    # zero-or-more</code></pre>

<p>Because separated lists are such a common component of grammars, Regexp::Grammars provides cleaner ways to specify them:</p>

<pre><code>    &lt;rule: list&gt;
        &lt;[item]&gt;+ % &lt;separator&gt;      # one-or-more

    &lt;rule: list_zom&gt;
        &lt;[item]&gt;* % &lt;separator&gt;      # zero-or-more</code></pre>

<p>Note that these are just regular repetition qualifiers (i.e. <code>+</code> and <code>*</code>) applied to a subrule (<code>&lt;[item]&gt;</code>), with a <code>%</code> modifier after them to specify the required separator between the repeated matches.</p>

<p>The number of repetitions matched is controlled both by the nature of the qualifier (<code>+</code> vs <code>*</code>) and by the subrule specified after the <code>%</code>. The qualified subrule will be repeatedly matched for as long as its qualifier allows, provided that the second subrule also matches <i>between</i> those repetitions.</p>

<p>For example, you can match a parenthesized sequence of one-or-more numbers separated by commas, such as:</p>

<pre><code>    (1, 2, 3, 4, 13, 91)        # Numbers separated by commas (and spaces)</code></pre>

<p>with:</p>

<pre><code>    &lt;rule: number_list&gt;

        \(  &lt;[number]&gt;+ % &lt;comma&gt;  \)

    &lt;token: number&gt;  \d+
    &lt;token: comma&gt;   ,</code></pre>

<p>Note that any spaces round the commas will be ignored because <code>&lt;number_list&gt;</code> is specified as a rule and the <code>+%</code> specifier has spaces within and around it. To disallow spaces around the commas, make sure there are no spaces in or around the <code>+%</code>:</p>

<pre><code>    &lt;rule: number_list_no_spaces&gt;

        \( &lt;[number]&gt;+%&lt;comma&gt; \)</code></pre>

<p>(or else specify the rule as a token instead).</p>

<p>Because the <code>%</code> is a modifier applied to a qualifier, you can modify <i>any</i> other repetition qualifier in the same way. For example:</p>

<pre><code>    &lt;[item]&gt;{2,4} % &lt;sep&gt;   # two-to-four items, separated

    &lt;[item]&gt;{7}   % &lt;sep&gt;   # exactly 7 items, separated

    &lt;[item]&gt;{10,}? % &lt;sep&gt;   # minimum of 10 or more items, separated</code></pre>

<p>You can even do this:</p>

<pre><code>    &lt;[item]&gt;? % &lt;sep&gt;       # one-or-zero items, (theoretically) separated</code></pre>

<p>though the separator specification is, of course, meaningless in that case as it will never be needed to separate a maximum of one item.</p>

<p>Within a Regexp::Grammars regex a simple <code>%</code> is always metasyntax, so it cannot be used to match a literal <code>&#39;%&#39;</code>. Any attempt to do so is immediately fatal when the regex is compiled:</p>

<pre><code>    &lt;token: percentage&gt;
        \d{1,3} %                # Fatal. Will not match &quot;7%&quot;, &quot;100%&quot;, etc.

    &lt;token: perl_hash&gt;
        % &lt;ident&gt;                # Fatal. Will not match &quot;%foo&quot;, &quot;%bar&quot;, etc.

    &lt;token: perl_mod&gt;
        &lt;expr&gt; % &lt;expr&gt;          # Fatal. Will not match &quot;$n % 2&quot;, etc.</code></pre>

<p>If you need to match a literal <code>%</code> immediately after a repetition, quote it with a backslash:</p>

<pre><code>    &lt;token: percentage&gt;
        \d{1,3} \%               # Okay. Will match &quot;7%&quot;, &quot;100%&quot;, etc.

    &lt;token: perl_hash&gt;
        \% &lt;ident&gt;               # Okay. Will match &quot;%foo&quot;, &quot;%bar&quot;, etc.

    &lt;token: perl_mod&gt;
        &lt;expr&gt; \% &lt;expr&gt;         # Okay. Will match &quot;$n % 2&quot;, etc.</code></pre>

<p>Note that it&#39;s usually necessary to use the <code>&lt;[...]&gt;</code> form for the repeated items being matched, so that all of them are saved in the result hash. You can also save all the separators (if they&#39;re important) by specifying them as a list-like subrule too:</p>

<pre><code>    \(  &lt;[number]&gt;* % &lt;[comma]&gt;  \)  # save numbers *and* separators</code></pre>

<p>The repeated item <i>must</i> be specified as a subrule call of some kind (i.e. in angles), but the separators may be specified either as a subrule or as a raw bracketed pattern (i.e. brackets without any nested subrule calls). For example:</p>

<pre><code>    &lt;[number]&gt;* % ( , | : )    # Numbers separated by commas or colons

    &lt;[number]&gt;* % [,:]         # Same, but more efficiently matched</code></pre>

<p>The separator should always be specified within matched delimiters of some kind: either matching <code>&lt;...&gt;</code> or matching <code>(...)</code> or matching <code>[...]</code>. Simple, non-bracketed separators will sometimes also work:</p>

<pre><code>    &lt;[number]&gt;+ % ,</code></pre>

<p>but not always:</p>

<pre><code>    &lt;[number]&gt;+ % ,\s+     # Oops! Separator is just: ,</code></pre>

<p>This is because of the limited way in which the module internally parses ordinary regex components (i.e. without full understanding of their implicit precedence). As a consequence, consistently placing brackets around any separator is a much safer approach:</p>

<pre><code>    &lt;[number]&gt;+ % (,\s+)</code></pre>

<p>You can also use a simple pattern on the left of the <code>%</code> as the item matcher, but in this case it <i>must always</i> be aliased into a list-collecting subrule, like so:</p>

<pre><code>    &lt;[item=(\d+)]&gt;* % [,]</code></pre>

<p>Note that, for backwards compatibility with earlier versions of Regexp::Grammars, the <code>+%</code> operator can also be written: <code>**</code>. However, there can be no space between the two asterisks of this variant. That is:</p>

<pre><code>    &lt;[item]&gt; ** &lt;sep&gt;      # same as &lt;[item]&gt;* % &lt;sep&gt;

    &lt;[item]&gt;* * &lt;sep&gt;      # error (two * qualifiers in a row)</code></pre>

<h3 id="Matching-separated-lists-with-a-trailing-separator"><a id="Matching2"></a>Matching separated lists with a trailing separator</h3>

<p>Some languages allow a separated list to include an extra trailing separator. For example:</p>

<pre><code>    ~/bin/perl5/        # Trailing /-separator in filepath
    (1,2,3,)            # Trailing ,-separator in Perl list</code></pre>

<p>To match such constructs using the <code>%</code> operator, you would need to add something to explicitly match the optional trailing separator:</p>

<pre><code>    &lt;dir&gt;+ % [/] [/]?    # Slash-separated dirs, then optional final slash

    &lt;elem&gt;+ % [,] [,]?   # Comma-separated elems, then optional final comma</code></pre>

<p>which is tedious.</p>

<p>So the module also supports a second kind of &quot;separated list&quot; operator, that allows an optional trailing separator as well: the <code>%%</code> operator. THis operator behaves exactly like the <code>%</code> operator, except that it also matches a final trailing separator, if one is present.</p>

<p>So the previous examples could be (better) written as:</p>

<pre><code>    &lt;dir&gt;+ %% [/]     # Slash-separated dirs, with optional final slash

    &lt;elem&gt;+ %% [,]    # Comma-separated elems, with optional final comma</code></pre>

<h2 id="Matching-hash-keys"><a id="Matching3"></a>Matching hash keys</h2>

<p>In some situations a grammar may need a rule that matches dozens, hundreds, or even thousands of one-word alternatives. For example, when matching command names, or valid userids, or English words. In such cases it is often impractical (and always inefficient) to list all the alternatives between <code>|</code> alternators:</p>

<pre><code>    &lt;rule: shell_cmd&gt;
        a2p | ac | apply | ar | automake | awk | ...
        # ...and 400 lines later
        ... | zdiff | zgrep | zip | zmore | zsh

    &lt;rule: valid_word&gt;
        a | aa | aal | aalii | aam | aardvark | aardwolf | aba | ...
        # ...and 40,000 lines later...
        ... | zymotize | zymotoxic | zymurgy | zythem | zythum</code></pre>

<p>To simplify such cases, Regexp::Grammars provides a special construct that allows you to specify all the alternatives as the keys of a normal hash. The syntax for that construct is simply to put the hash name inside angle brackets (with no space between the angles and the hash name).</p>

<p>Which means that the rules in the previous example could also be written:</p>

<pre><code>    &lt;rule: shell_cmd&gt;
        &lt;%cmds&gt;

    &lt;rule: valid_word&gt;
        &lt;%dict&gt;</code></pre>

<p>provided that the two hashes (<code>%cmds</code> and <code>%dict</code>) are visible in the scope where the grammar is created.</p>

<p>Matching a hash key in this way is typically <i>significantly</i> faster than matching a large set of alternations. Specifically, it is <i>O(length of longest potential key) ^ 2</i>, instead of <i>O(number of keys)</i>.</p>

<p>Internally, the construct is converted to something equivalent to:</p>

<pre><code>    &lt;rule: shell_cmd&gt;
        (&lt;.hk&gt;)  &lt;require: (?{ exists $cmds{$CAPTURE} })&gt;

    &lt;rule: valid_word&gt;
        (&lt;.hk&gt;)  &lt;require: (?{ exists $dict{$CAPTURE} })&gt;</code></pre>

<p>The special <code>&lt;hk&gt;</code> rule is created automatically, and defaults to <code>\S+</code>, but you can also define it explicitly to handle other kinds of keys. For example:</p>

<pre><code>    &lt;rule: hk&gt;
        [^\n]+        # Key may be any number of chars on a single line

    &lt;rule: hk&gt;
        [ACGT]{10,}   # Key is a base sequence of at least 10 pairs</code></pre>

<p>Alternatively, you can specify a different key-matching pattern for each hash you&#39;re matching, by placing the required pattern in braces immediately after the hash name. For example:</p>

<pre><code>    &lt;rule: client_name&gt;
        # Valid keys match &lt;.hk&gt; (default or explicitly specified)
        &lt;%clients&gt;

    &lt;rule: shell_cmd&gt;
        # Valid keys contain only word chars, hyphen, slash, or dot...
        &lt;%cmds { [\w-/.]+ }&gt;

    &lt;rule: valid_word&gt;
        # Valid keys contain only alphas or internal hyphen or apostrophe...
        &lt;%dict{ (?i: (?:[a-z]+[-&#39;])* [a-z]+ ) }&gt;

    &lt;rule: DNA_sequence&gt;
        # Valid keys are base sequences of at least 10 pairs...
        &lt;%sequences{[ACGT]{10,}}&gt;</code></pre>

<p>This second approach to key-matching is preferred, because it localizes any non-standard key-matching behaviour to each individual hash.</p>

<p>Note that changes in the compilation process from Perl 5.18 onwards mean that in some cases the <code>&lt;%hash&gt;</code> construct only works reliably if the hash itself is declared at the outermost lexical scope (i.e. file scope).</p>

<p>Specifically, if the regex grammar does not include any interpolated scalars or arrays <i>and</i> the hash was declared within a subroutine (even within the same subroutine as the regex grammar that uses it), the regex will not be able to &quot;see&quot; the hash variable at compile-time. This will produce a <i>&quot;Global symbol &quot;%hash&quot; requires explicit package name&quot;</i> compile-time error. For example:</p>

<pre><code>    sub build_keyword_parser {
        # Hash declared inside subroutine...
        my %keywords = (foo =&gt; 1, bar =&gt; 1);

        # ...then used in &lt;%hash&gt; construct within uninterpolated regex...
        return qr{
                    ^&lt;keyword&gt;$
                    &lt;rule: keyword&gt; &lt;%keywords&gt;
                 }x;

        # ...produces compile-time error
    }</code></pre>

<p>The solution is to place the hash outside the subroutine containing the grammar:</p>

<pre><code>    # Hash declared OUTSIDE subroutine...
    my %keywords = (foo =&gt; 1, bar =&gt; 1);

    sub build_keyword_parser {
        return qr{
                    ^&lt;keyword&gt;$
                    &lt;rule: keyword&gt; &lt;%keywords&gt;
                 }x;
    }</code></pre>

<p>...or else to explicitly interpolate at least one scalar (even just a scalar containing an empty string):</p>

<pre><code>    sub build_keyword_parser {
        my %keywords = (foo =&gt; 1, bar =&gt; 1);
        my $DEFER_REGEX_COMPILATION = &quot;&quot;;

        return qr{
                    ^&lt;keyword&gt;$
                    &lt;rule: keyword&gt; &lt;%keywords&gt;

                    $DEFER_REGEX_COMPILATION
                 }x;
    }</code></pre>

<h2 id="Rematching-subrule-results"><a id="Rematching"></a>Rematching subrule results</h2>

<p>Sometimes it is useful to be able to rematch a string that has previously been matched by some earlier subrule. For example, consider a rule to match shell-like control blocks:</p>

<pre><code>    &lt;rule: control_block&gt;
          for   &lt;expr&gt; &lt;[command]&gt;+ endfor
        | while &lt;expr&gt; &lt;[command]&gt;+ endwhile
        | if    &lt;expr&gt; &lt;[command]&gt;+ endif
        | with  &lt;expr&gt; &lt;[command]&gt;+ endwith</code></pre>

<p>This would be much tidier if we could factor out the command names (which are the only differences between the four alternatives). The problem is that the obvious solution:</p>

<pre><code>    &lt;rule: control_block&gt;
        &lt;keyword&gt; &lt;expr&gt;
            &lt;[command]&gt;+
        end&lt;keyword&gt;</code></pre>

<p>doesn&#39;t work, because it would also match an incorrect input like:</p>

<pre><code>    for 1..10
        echo $n
        ls subdir/$n
    endif</code></pre>

<p>We need some way to ensure that the <code>&lt;keyword&gt;</code> matched immediately after &quot;end&quot; is the same <code>&lt;keyword&gt;</code> that was initially matched.</p>

<p>That&#39;s not difficult, because the first <code>&lt;keyword&gt;</code> will have captured what it matched into <code>$MATCH{keyword}</code>, so we could just write:</p>

<pre><code>    &lt;rule: control_block&gt;
        &lt;keyword&gt; &lt;expr&gt;
            &lt;[command]&gt;+
        end(??{quotemeta $MATCH{keyword}})</code></pre>

<p>This is such a useful technique, yet so ugly, scary, and prone to error, that Regexp::Grammars provides a cleaner equivalent:</p>

<pre><code>    &lt;rule: control_block&gt;
        &lt;keyword&gt; &lt;expr&gt;
            &lt;[command]&gt;+
        end&lt;\_keyword&gt;</code></pre>

<p>A directive of the form <code>&lt;\_<i>IDENTIFIER</i>&gt;</code> is known as a &quot;matchref&quot; (an abbreviation of &quot;%MATCH-supplied backreference&quot;). Matchrefs always attempt to match, as a literal, the current value of <code>$MATCH{<i>IDENTIFIER</i>}</code>.</p>

<p>By default, a matchref does not capture what it matches, but you can have it do so by giving it an alias:</p>

<pre><code>    &lt;token: delimited_string&gt;
        &lt;ldelim=str_delim&gt;  .*?  &lt;rdelim=\_ldelim&gt;

    &lt;token: str_delim&gt; [&quot;&#39;`]</code></pre>

<p>At first glance this doesn&#39;t seem very useful as, by definition, <code>$MATCH{ldelim}</code> and <code>$MATCH{rdelim}</code> must necessarily always end up with identical values. However, it can be useful if the rule also has other alternatives and you want to create a consistent internal representation for those alternatives, like so:</p>

<pre><code>    &lt;token: delimited_string&gt;
          &lt;ldelim=str_delim&gt;  .*?  &lt;rdelim=\_ldelim&gt;
        | &lt;ldelim=( \[ )      .*?  &lt;rdelim=( \] )
        | &lt;ldelim=( \{ )      .*?  &lt;rdelim=( \} )
        | &lt;ldelim=( \( )      .*?  &lt;rdelim=( \) )
        | &lt;ldelim=( \&lt; )      .*?  &lt;rdelim=( \&gt; )</code></pre>

<p>You can also force a matchref to save repeated matches as a nested array, in the usual way:</p>

<pre><code>    &lt;token: marked_text&gt;
        &lt;marker&gt; &lt;text&gt; &lt;[endmarkers=\_marker]&gt;+</code></pre>

<p>Be careful though, as the following will not do as you may expect:</p>

<pre><code>        &lt;[marker]&gt;+ &lt;text&gt; &lt;[endmarkers=\_marker]&gt;+</code></pre>

<p>because the value of <code>$MATCH{marker}</code> will be an array reference, which the matchref will flatten and concatenate, then match the resulting string as a literal, which will mean the previous example will match endmarkers that are exact multiples of the complete start marker, rather than endmarkers that consist of any number of repetitions of the individual start marker delimiter. So:</p>

<pre><code>        &quot;&quot;text here&quot;&quot;
        &quot;&quot;text here&quot;&quot;&quot;&quot;
        &quot;&quot;text here&quot;&quot;&quot;&quot;&quot;&quot;</code></pre>

<p>but not:</p>

<pre><code>        &quot;&quot;text here&quot;&quot;&quot;
        &quot;&quot;text here&quot;&quot;&quot;&quot;&quot;</code></pre>

<p>Uneven start and end markers such as these are extremely unusual, so this problem rarely arises in practice.</p>

<p><i><b>Note:</b> Prior to Regexp::Grammars version 1.020, the syntax for matchrefs was <code>&lt;\<i>IDENTIFIER</i>&gt;</code> instead of <code>&lt;\_<i>IDENTIFIER</i>&gt;</code>. This created problems when the identifier started with any of <code>l</code>, <code>u</code>, <code>L</code>, <code>U</code>, <code>Q</code>, or <code>E</code>, so the syntax has had to be altered in a backwards incompatible way. It will not be altered again. </i></p>

<h2 id="Rematching-balanced-delimiters"><a id="Rematching1"></a>Rematching balanced delimiters</h2>

<p>Consider the example in the previous section:</p>

<pre><code>    &lt;token: delimited_string&gt;
          &lt;ldelim=str_delim&gt;  .*?  &lt;rdelim=\_ldelim&gt;
        | &lt;ldelim=( \[ )      .*?  &lt;rdelim=( \] )
        | &lt;ldelim=( \{ )      .*?  &lt;rdelim=( \} )
        | &lt;ldelim=( \( )      .*?  &lt;rdelim=( \) )
        | &lt;ldelim=( \&lt; )      .*?  &lt;rdelim=( \&gt; )</code></pre>

<p>The repeated pattern of the last four alternatives is gauling, but we can&#39;t just refactor those delimiters as well:</p>

<pre><code>    &lt;token: delimited_string&gt;
          &lt;ldelim=str_delim&gt;  .*?  &lt;rdelim=\_ldelim&gt;
        | &lt;ldelim=bracket&gt;    .*?  &lt;rdelim=\_ldelim&gt;</code></pre>

<p>because that would incorrectly match:</p>

<pre><code>    { delimited content here {</code></pre>

<p>while failing to match:</p>

<pre><code>    { delimited content here }</code></pre>

<p>To refactor balanced delimiters like those, we need a second kind of matchref; one that&#39;s a little smarter.</p>

<p>Or, preferably, a lot smarter...because there are many other kinds of balanced delimiters, apart from single brackets. For example:</p>

<pre><code>      {{{ delimited content here }}}
       /* delimited content here */
       (* delimited content here *)
       `` delimited content here &#39;&#39;
       if delimited content here fi</code></pre>

<p>The common characteristic of these delimiter pairs is that the closing delimiter is the <i>inverse</i> of the opening delimiter: the sequence of characters is reversed and certain characters (mainly brackets, but also single-quotes/backticks) are mirror-reflected.</p>

<p>Regexp::Grammars supports the parsing of such delimiters with a construct known as an <i>invertref</i>, which is specified using the <code>&lt;/<i>IDENT</i>&gt;</code> directive. An invertref acts very like a <a href="./Regexp::Grammars.html#Rematching-subrule-results">matchref</a>, except that it does not convert to:</p>

<pre><code>    (??{ quotemeta( $MATCH{I&lt;IDENT&gt;} ) })</code></pre>

<p>but rather to:</p>

<pre><code>    (??{ quotemeta( inverse( $MATCH{I&lt;IDENT&gt; ))} })</code></pre>

<p>With this directive available, the balanced delimiters of the previous example can be refactored to:</p>

<pre><code>    &lt;token: delimited_string&gt;
          &lt;ldelim=str_delim&gt;  .*?  &lt;rdelim=\_ldelim&gt;
        | &lt;ldelim=( [[{(&lt;] )  .*?  &lt;rdelim=/ldelim&gt;</code></pre>

<p>Like matchrefs, invertrefs come in the usual range of flavours:</p>

<pre><code>    &lt;/ident&gt;            # Match the inverse of $MATCH{ident}
    &lt;ALIAS=/ident&gt;      # Match inverse and capture to $MATCH{ident}
    &lt;[ALIAS=/ident]&gt;    # Match inverse and push on @{$MATCH{ident}}</code></pre>

<p>The character pairs that are reversed during mirroring are: <code>{</code> and <code>}</code>, <code>[</code> and <code>]</code>, <code>(</code> and <code>)</code>, <code>&lt;</code> and <code>&gt;</code>, <code>&Acirc;&laquo;</code> and <code>&Acirc;&raquo;</code>, <code>`</code> and <code>&#39;</code>.</p>

<p>The following mnemonics may be useful in distinguishing inverserefs from backrefs: a backref starts with a <code>\</code> (just like the standard Perl regex backrefs <code>\1</code> and <code>\g{-2}</code> and <code>\k&lt;name&gt;</code>), whereas an inverseref starts with a <code>/</code> (like an HTML or XML closing tag). Or just remember that <code>&lt;\_IDENT&gt;</code> is &quot;match the same again&quot;, and if you want &quot;the same again, only mirrored&quot; instead, just mirror the <code>\</code> to get <code>&lt;/IDENT&gt;</code>.</p>

<h2 id="Rematching-parametric-results-and-delimiters"><a id="Rematching2"></a>Rematching parametric results and delimiters</h2>

<p>The <code>&lt;\_<i>IDENTIFIER</i>&gt;</code> and <code>&lt;/<i>IDENTIFIER</i>&gt;</code> mechanisms normally locate the literal to be matched by looking in <code>$MATCH{<i>IDENTIFIER</i>}</code>.</p>

<p>However, you can cause them to look in <code>$ARG{<i>IDENTIFIER</i>}</code> instead, by prefixing the identifier with a single <code>:</code>. This is especially useful when refactoring subrules. For example, instead of:</p>

<pre><code>    &lt;rule: Command&gt;
        &lt;Keyword&gt;  &lt;CommandBody&gt;  end_ &lt;\_Keyword&gt;

    &lt;rule: Placeholder&gt;
        &lt;Keyword&gt;    \.\.\.   end_ &lt;\_Keyword&gt;</code></pre>

<p>you could parameterize the Terminator rule, like so:</p>

<pre><code>    &lt;rule: Command&gt;
        &lt;Keyword&gt;  &lt;CommandBody&gt;  &lt;Terminator(:Keyword)&gt;

    &lt;rule: Placeholder&gt;
        &lt;Keyword&gt;    \.\.\.   &lt;Terminator(:Keyword)&gt;

    &lt;token: Terminator&gt;
        end_ &lt;\:Keyword&gt;</code></pre>

<h2 id="Tracking-and-reporting-match-positions"><a id="Tracking"></a>Tracking and reporting match positions</h2>

<p>Regexp::Grammars automatically predefines a special token that makes it easy to track exactly where in its input a particular subrule matches. That token is: <code>&lt;matchpos&gt;</code>.</p>

<p>The <code>&lt;matchpos&gt;</code> token implements a zero-width match that never fails. It always returns the current index within the string that the grammar is matching.</p>

<p>So, for example you could have your <code>&lt;delimited_text&gt;</code> subrule detect and report unterminated text like so:</p>

<pre><code>    &lt;token: delimited_text&gt;
        qq? &lt;delim&gt; &lt;text=(.*?)&gt; &lt;/delim&gt;
    |
        &lt;matchpos&gt; qq? &lt;delim&gt;
        &lt;error: (?{&quot;Unterminated string starting at index $MATCH{matchpos}&quot;})&gt;</code></pre>

<p>Matching <code>&lt;matchpos&gt;</code> in the second alternative causes <code>$MATCH{matchpos}</code> to contain the position in the string at which the <code>&lt;matchpos&gt;</code> subrule was matched (in this example: the start of the unterminated text).</p>

<p>If you want the line number instead of the string index, use the predefined <code>&lt;matchline&gt;</code> subrule instead:</p>

<pre><code>    &lt;token: delimited_text&gt;
              qq? &lt;delim&gt; &lt;text=(.*?)&gt; &lt;/delim&gt;
    |   &lt;matchline&gt; qq? &lt;delim&gt;
        &lt;error: (?{&quot;Unterminated string starting at line $MATCH{matchline}&quot;})&gt;</code></pre>

<p>Note that the line numbers returned by <code>&lt;matchline&gt;</code> start at 1 (not at zero, as with <code>&lt;matchpos&gt;</code>).</p>

<p>The <code>&lt;matchpos&gt;</code> and <code>&lt;matchline&gt;</code> subrules are just like any other subrules; you can alias them (<code>&lt;started_at=matchpos&gt;</code>) or match them repeatedly ( <code>(?: &lt;[matchline]&gt; &lt;[item]&gt; )++</code>), etc.</p>

<h1 id="Autoactions">Autoactions</h1>

<p>The module also supports event-based parsing. You can specify a grammar in the usual way and then, for a particular parse, layer a collection of call-backs (known as &quot;autoactions&quot;) over the grammar to handle the data as it is parsed.</p>

<p>Normally, a grammar rule returns the result hash it has accumulated (or whatever else was aliased to <code>MATCH=</code> within the rule). However, you can specify an autoaction object before the grammar is matched.</p>

<p>Once the autoaction object is specified, every time a rule succeeds during the parse, its result is passed to the object via one of its methods; specifically it is passed to the method whose name is the same as the rule&#39;s.</p>

<p>For example, suppose you had a grammar that recognizes simple algebraic expressions:</p>

<pre><code>    my $expr_parser = do{
        use Regexp::Grammars;
        qr{
            &lt;Expr&gt;

            &lt;rule: Expr&gt;       &lt;[Operand=Mult]&gt;+ % &lt;[Op=(\+|\-)]&gt;

            &lt;rule: Mult&gt;       &lt;[Operand=Pow]&gt;+  % &lt;[Op=(\*|/|%)]&gt;

            &lt;rule: Pow&gt;        &lt;[Operand=Term]&gt;+ % &lt;Op=(\^)&gt;

            &lt;rule: Term&gt;          &lt;MATCH=Literal&gt;
                       |       \( &lt;MATCH=Expr&gt; \)

            &lt;token: Literal&gt;   &lt;MATCH=( [+-]? \d++ (?: \. \d++ )?+ )&gt;
        }xms
    };</code></pre>

<p>You could convert this grammar to a calculator, by installing a set of autoactions that convert each rule&#39;s result hash to the corresponding value of the sub-expression that the rule just parsed. To do that, you would create a class with methods whose names match the rules whose results you want to change. For example:</p>

<pre><code>    package Calculator;
    use List::Util qw&lt; reduce &gt;;

    sub new {
        my ($class) = @_;

        return bless {}, $class
    }

    sub Answer {
        my ($self, $result_hash) = @_;

        my $sum = shift @{$result_hash-&gt;{Operand}};

        for my $term (@{$result_hash-&gt;{Operand}}) {
            my $op = shift @{$result_hash-&gt;{Op}};
            if ($op eq &#39;+&#39;) { $sum += $term; }
            else            { $sum -= $term; }
        }

        return $sum;
    }

    sub Mult {
        my ($self, $result_hash) = @_;

        return reduce { eval($a . shift(@{$result_hash-&gt;{Op}}) . $b) }
                      @{$result_hash-&gt;{Operand}};
    }

    sub Pow {
        my ($self, $result_hash) = @_;

        return reduce { $b ** $a } reverse @{$result_hash-&gt;{Operand}};
    }</code></pre>

<p>Objects of this class (and indeed the class itself) now have methods corresponding to some of the rules in the expression grammar. To apply those methods to the results of the rules (as they parse) you simply install an object as the &quot;autoaction&quot; handler, immediately before you initiate the parse:</p>

<pre><code>    if ($text ~= $expr_parser-&gt;with_actions(Calculator-&gt;new)) {
        say $/{Answer};   # Now prints the result of the expression
    }</code></pre>

<p>The <code>with_actions()</code> method expects to be passed an object or classname. This object or class will be installed as the autoaction handler for the next match against any grammar. After that match, the handler will be uninstalled. <code>with_actions()</code> returns the grammar it&#39;s called on, making it easy to call it as part of a match (which is the recommended idiom).</p>

<p>With a <code>Calculator</code> object set as the autoaction handler, whenever the <code>Answer</code>, <code>Mult</code>, or <code>Pow</code> rule of the grammar matches, the corresponding <code>Answer</code>, <code>Mult</code>, or <code>Pow</code> method of the <code>Calculator</code> object will be called (with the rule&#39;s result value passed as its only argument), and the result of the method will be used as the result of the rule.</p>

<p>Note that nothing new happens when a <code>Term</code> or <code>Literal</code> rule matches, because the <code>Calculator</code> object doesn&#39;t have methods with those names.</p>

<p>The overall effect, then, is to allow you to specify a grammar without rule-specific bahaviours and then, later, specify a set of final actions (as methods) for some or all of the rules of the grammar.</p>

<p>Note that, if a particular callback method returns <code>undef</code>, the result of the corresponding rule will be passed through without modification.</p>

<h1 id="Named-grammars"><a id="Named"></a>Named grammars</h1>

<p>All the grammars shown so far are confined to a single regex. However, Regexp::Grammars also provides a mechanism that allows you to defined named grammars, which can then be imported into other regexes. This gives the a way of modularizing common grammatical components.</p>

<h2 id="Defining-a-named-grammar"><a id="Defining2"></a>Defining a named grammar</h2>

<p>You can create a named grammar using the <code>&lt;grammar:...&gt;</code> directive. This directive must appear before the first rule definition in the grammar, and instead of any start-rule. For example:</p>

<pre><code>    qr{
        &lt;grammar: List::Generic&gt;

        &lt;rule: List&gt;
            &lt;[MATCH=Item]&gt;+ % &lt;Separator&gt;

        &lt;rule: Item&gt;
            \S++

        &lt;token: Separator&gt;
            \s* , \s*
    }x;</code></pre>

<p>This creates a grammar named <code>List::Generic</code>, and installs it in the module&#39;s internal caches, for future reference.</p>

<p>Note that there is no need (or reason) to assign the resulting regex to a variable, as the named grammar cannot itself be matched against.</p>

<h2 id="Using-a-named-grammar"><a id="Using"></a>Using a named grammar</h2>

<p>To make use of a named grammar, you need to incorporate it into another grammar, by inheritance. To do that, use the <code>&lt;extends:...&gt;</code> directive, like so:</p>

<pre><code>    my $parser = qr{
        &lt;extends: List::Generic&gt;

        &lt;List&gt;
    }x;</code></pre>

<p>The <code>&lt;extends:...&gt;</code> directive incorporates the rules defined in the specified grammar into the current regex. You can then call any of those rules in the start-pattern.</p>

<h2 id="Overriding-an-inherited-rule-or-token"><a id="Overriding"></a>Overriding an inherited rule or token</h2>

<p>Subrule dispatch within a grammar is always polymorphic. That is, when a subrule is called, the most-derived rule of the same name within the grammar&#39;s hierarchy is invoked.</p>

<p>So, to replace a particular rule within grammar, you simply need to inherit that grammar and specify new, more-specific versions of any rules you want to change. For example:</p>

<pre><code>    my $list_of_integers = qr{
        &lt;List&gt;

        # Inherit rules from base grammar...
        &lt;extends: List::Generic&gt;

        # Replace Item rule from List::Generic...
        &lt;rule: Item&gt;
            [+-]? \d++
    }x;</code></pre>

<p>You can also use <code>&lt;extends:...&gt;</code> in other named grammars, to create hierarchies:</p>

<pre><code>    qr{
        &lt;grammar: List::Integral&gt;
        &lt;extends: List::Generic&gt;

        &lt;token: Item&gt;
            [+-]? &lt;MATCH=(&lt;.Digit&gt;+)&gt;

        &lt;token: Digit&gt;
            \d
    }x;

    qr{
        &lt;grammar: List::ColonSeparated&gt;
        &lt;extends: List::Generic&gt;

        &lt;token: Separator&gt;
            \s* : \s*
    }x;

    qr{
        &lt;grammar: List::Integral::ColonSeparated&gt;
        &lt;extends: List::Integral&gt;
        &lt;extends: List::ColonSeparated&gt;
    }x;</code></pre>

<p>As shown in the previous example, Regexp::Grammars allows you to multiply inherit two (or more) base grammars. For example, the <code>List::Integral::ColonSeparated</code> grammar takes the definitions of <code>List</code> and <code>Item</code> from the <code>List::Integral</code> grammar, and the definition of <code>Separator</code> from <code>List::ColonSeparated</code>.</p>

<p>Note that grammars dispatch subrule calls using C3 method lookup, rather than Perl&#39;s older DFS lookup. That&#39;s why <code>List::Integral::ColonSeparated</code> correctly gets the more-specific <code>Separator</code> rule defined in <code>List::ColonSeparated</code>, rather than the more-generic version defined in <code>List::Generic</code> (via <code>List::Integral</code>). See <code>perldoc mro</code> for more discussion of the C3 dispatch algorithm.</p>

<h2 id="Augmenting-an-inherited-rule-or-token"><a id="Augmenting"></a>Augmenting an inherited rule or token</h2>

<p>Instead of replacing an inherited rule, you can augment it.</p>

<p>For example, if you need a grammar for lists of hexademical numbers, you could inherit the behaviour of <code>List::Integral</code> and add the hex digits to its <code>Digit</code> token:</p>

<pre><code>    my $list_of_hexadecimal = qr{
        &lt;List&gt;

        &lt;extends: List::Integral&gt;

        &lt;token: Digit&gt;
            &lt;List::Integral::Digit&gt;
          | [A-Fa-f]
    }x;</code></pre>

<p>If you call a subrule using a fully qualified name (such as <code>&lt;List::Integral::Digit&gt;</code>), the grammar calls that version of the rule, rather than the most-derived version.</p>

<h2 id="Debugging-named-grammars"><a id="Debugging"></a>Debugging named grammars</h2>

<p>Named grammars are independent of each other, even when inherited. This means that, if debugging is enabled in a derived grammar, it will not be active in any rules inherited from a base grammar, unless the base grammar also included a <code>&lt;debug:...&gt;</code> directive.</p>

<p>This is a deliberate design decision, as activating the debugger adds a significant amount of code to each grammar&#39;s implementation, which is detrimental to the matching performance of the resulting regexes.</p>

<p>If you need to debug a named grammar, the best approach is to include a <code>&lt;debug: same&gt;</code> directive at the start of the grammar. The presence of this directive will ensure the necessary extra debugging code is included in the regex implementing the grammar, while setting <code>same</code> mode will ensure that the debugging mode isn&#39;t altered when the matcher uses the inherited rules.</p>

<h1 id="Common-parsing-techniques"><a id="Common"></a>Common parsing techniques</h1>

<h2 id="Result-distillation"><a id="Result"></a>Result distillation</h2>

<p>Normally, calls to subrules produce nested result-hashes within the current result-hash. Those nested hashes always have at least one automatically supplied key (<code>&quot;&quot;</code>), whose value is the entire substring that the subrule matched.</p>

<p>If there are no other nested captures within the subrule, there will be no other keys in the result-hash. This would be annoying as a typical nested grammar would then produce results consisting of hashes of hashes, with each nested hash having only a single key (<code>&quot;&quot;</code>). This in turn would make postprocessing the result-hash (in <code>%/</code>) far more complicated than it needs to be.</p>

<p>To avoid this behaviour, if a subrule&#39;s result-hash doesn&#39;t contain any keys except <code>&quot;&quot;</code>, the module &quot;flattens&quot; the result-hash, by replacing it with the value of its single key.</p>

<p>So, for example, the grammar:</p>

<pre><code>    mv \s* &lt;from&gt; \s* &lt;to&gt;

    &lt;rule: from&gt;   [\w/.-]+
    &lt;rule: to&gt;     [\w/.-]+</code></pre>

<p><i>doesn&#39;t</i> return a result-hash like this:</p>

<pre><code>    {
        &quot;&quot;     =&gt; &#39;mv /usr/local/lib/libhuh.dylib  /dev/null/badlib&#39;,
        &#39;from&#39; =&gt; { &quot;&quot; =&gt; &#39;/usr/local/lib/libhuh.dylib&#39; },
        &#39;to&#39;   =&gt; { &quot;&quot; =&gt; &#39;/dev/null/badlib&#39;            },
    }</code></pre>

<p>Instead, it returns:</p>

<pre><code>    {
        &quot;&quot;     =&gt; &#39;mv /usr/local/lib/libhuh.dylib  /dev/null/badlib&#39;,
        &#39;from&#39; =&gt; &#39;/usr/local/lib/libhuh.dylib&#39;,
        &#39;to&#39;   =&gt; &#39;/dev/null/badlib&#39;,
    }</code></pre>

<p>That is, because the <code>&#39;from&#39;</code> and <code>&#39;to&#39;</code> subhashes each have only a single entry, they are each &quot;flattened&quot; to the value of that entry.</p>

<p>This flattening also occurs if a result-hash contains only &quot;private&quot; keys (i.e. keys starting with underscores). For example:</p>

<pre><code>    mv \s* &lt;from&gt; \s* &lt;to&gt;

    &lt;rule: from&gt;   &lt;_dir=path&gt;? &lt;_file=filename&gt;
    &lt;rule: to&gt;     &lt;_dir=path&gt;? &lt;_file=filename&gt;

    &lt;token: path&gt;      [\w/.-]*/
    &lt;token: filename&gt;  [\w.-]+</code></pre>

<p>Here, the <code>from</code> rule produces a result like this:</p>

<pre><code>    from =&gt; {
          &quot;&quot; =&gt; &#39;/usr/local/bin/perl&#39;,
        _dir =&gt; &#39;/usr/local/bin/&#39;,
       _file =&gt; &#39;perl&#39;,
    }</code></pre>

<p>which is automatically stripped of &quot;private&quot; keys, leaving:</p>

<pre><code>    from =&gt; {
          &quot;&quot; =&gt; &#39;/usr/local/bin/perl&#39;,
    }</code></pre>

<p>which is then automatically flattened to:</p>

<pre><code>    from =&gt; &#39;/usr/local/bin/perl&#39;</code></pre>

<h3 id="List-result-distillation"><a id="List1"></a>List result distillation</h3>

<p>A special case of result distillation occurs in a separated list, such as:</p>

<pre><code>    &lt;rule: List&gt;

        &lt;[Item]&gt;+ % &lt;[Sep=(,)]&gt;</code></pre>

<p>If this construct matches just a single item, the result hash will contain a single entry consisting of a nested array with a single value, like so:</p>

<pre><code>    { Item =&gt; [ &#39;data&#39; ] }</code></pre>

<p>Instead of returning this annoyingly nested data structure, you can tell Regexp::Grammars to flatten it to just the inner data with a special directive:</p>

<pre><code>    &lt;rule: List&gt;

        &lt;[Item]&gt;+ % &lt;[Sep=(,)]&gt;

        &lt;minimize:&gt;</code></pre>

<p>The <code>&lt;minimize:&gt;</code> directive examines the result hash (i.e. <code>%MATCH</code>). If that hash contains only a single entry, which is a reference to an array with a single value, then the directive assigns that single value directly to <code>$MATCH</code>, so that it will be returned instead of the usual result hash.</p>

<p>This means that a normal separated list still results in a hash containing all elements and separators, but a &quot;degenerate&quot; list of only one item results in just that single item.</p>

<h3 id="Manual-result-distillation"><a id="Manual"></a>Manual result distillation</h3>

<p>Regexp::Grammars also offers full manual control over the distillation process. If you use the reserved word <code>MATCH</code> as the alias for a subrule call:</p>

<pre><code>    &lt;MATCH=filename&gt;</code></pre>

<p>or a subpattern match:</p>

<pre><code>    &lt;MATCH=( \w+ )&gt;</code></pre>

<p>or a code block:</p>

<pre><code>    &lt;MATCH=(?{ 42 })&gt;</code></pre>

<p>then the current rule will treat the return value of that subrule, pattern, or code block as its complete result, and return that value instead of the usual result-hash it constructs. This is the case even if the result has other entries that would normally also be returned.</p>

<p>For example, consider a rule like:</p>

<pre><code>    &lt;rule: term&gt;
          &lt;MATCH=literal&gt;
        | &lt;left_paren&gt; &lt;MATCH=expr&gt; &lt;right_paren&gt;</code></pre>

<p>The use of <code>MATCH</code> aliases causes the rule to return either whatever <code>&lt;literal&gt;</code> returns, or whatever <code>&lt;expr&gt;</code> returns (provided it&#39;s between left and right parentheses).</p>

<p>Note that, in this second case, even though <code>&lt;left_paren&gt;</code> and <code>&lt;right_paren&gt;</code> <i>are</i> captured to the result-hash, they are not returned, because the <code>MATCH</code> alias overrides the normal &quot;return the result-hash&quot; semantics and returns only what its associated subrule (i.e. <code>&lt;expr&gt;</code>) produces.</p>

<p>Note also that the return value is only assigned, if the subrule call actually matches. For example:</p>

<pre><code>    &lt;rule: optional_names&gt;
        &lt;[MATCH=name]&gt;*</code></pre>

<p>If the repeated subrule call to <code>&lt;name&gt;</code> matches zero times, the return value of the <code>optional_names</code> rule will not be an empty array, because the <code>MATCH=</code> will not have executed at all. Instead, the default return value (an empty string) will be returned. If you had specifically wanted to return an empty array, you could use any of the following:</p>

<pre><code>    &lt;rule: optional_names&gt;
        &lt;MATCH=(?{ [] })&gt;     # Set up empty array before first match attempt
        &lt;[MATCH=name]&gt;*</code></pre>

<p>or:</p>

<pre><code>    &lt;rule: optional_names&gt;
        &lt;[MATCH=name]&gt;+       # Match one or more times
      |                       #          or
        &lt;MATCH=(?{ [] })&gt;     # Set up empty array, if no match</code></pre>

<h3 id="Programmatic-result-distillation"><a id="Programmatic"></a>Programmatic result distillation</h3>

<p>It&#39;s also possible to control what a rule returns from within a code block. Regexp::Grammars provides a set of reserved variables that give direct access to the result-hash.</p>

<p>The result-hash itself can be accessed as <code>%MATCH</code> within any code block inside a rule. For example:</p>

<pre><code>    &lt;rule: sum&gt;
        &lt;X=product&gt; \+ &lt;Y=product&gt;
            &lt;MATCH=(?{ $MATCH{X} + $MATCH{Y} })&gt;</code></pre>

<p>Here, the rule matches a product (aliased <code>&#39;X&#39;</code> in the result-hash), then a literal <code>&#39;+&#39;</code>, then another product (aliased to <code>&#39;Y&#39;</code> in the result-hash). The rule then executes the code block, which accesses the two saved values (as <code>$MATCH{X}</code> and <code>$MATCH{Y}</code>), adding them together. Because the block is itself aliased to <code>MATCH</code>, the sum produced by the block becomes the (only) result of the rule.</p>

<p>It is also possible to set the rule result from within a code block (instead of aliasing it). The special &quot;override&quot; return value is represented by the special variable <code>$MATCH</code>. So the previous example could be rewritten:</p>

<pre><code>    &lt;rule: sum&gt;
        &lt;X=product&gt; \+ &lt;Y=product&gt;
            (?{ $MATCH = $MATCH{X} + $MATCH{Y} })</code></pre>

<p>Both forms are identical in effect. Any assignment to <code>$MATCH</code> overrides the normal &quot;return all subrule results&quot; behaviour.</p>

<p>Assigning to <code>$MATCH</code> directly is particularly handy if the result may not always be &quot;distillable&quot;, for example:</p>

<pre><code>    &lt;rule: sum&gt;
        &lt;X=product&gt; \+ &lt;Y=product&gt;
            (?{ if (!ref $MATCH{X} &amp;&amp; !ref $MATCH{Y}) {
                    # Reduce to sum, if both terms are simple scalars...
                    $MATCH = $MATCH{X} + $MATCH{Y};
                }
                else {
                    # Return full syntax tree for non-simple case...
                    $MATCH{op} = &#39;+&#39;;
                }
            })</code></pre>

<p>Note that you can also partially override the subrule return behaviour. Normally, the subrule returns the complete text it matched as its context substring (i.e. under the &quot;empty key&quot;) in its result-hash. That is, of course, <code>$MATCH{&quot;&quot;}</code>, so you can override just that behaviour by directly assigning to that entry.</p>

<p>For example, if you have a rule that matches key/value pairs from a configuration file, you might prefer that any trailing comments not be included in the &quot;matched text&quot; entry of the rule&#39;s result-hash. You could hide such comments like so:</p>

<pre><code>    &lt;rule: config_line&gt;
        &lt;key&gt; : &lt;value&gt;  &lt;comment&gt;?
            (?{
                # Edit trailing comments out of &quot;matched text&quot; entry...
                $MATCH = &quot;$MATCH{key} : $MATCH{value}&quot;;
            })</code></pre>

<p>Some more examples of the uses of <code>$MATCH</code>:</p>

<pre><code>    &lt;rule: FuncDecl&gt;
      # Keyword  Name               Keep return the name (as a string)...
        func     &lt;Identifier&gt; ;     (?{ $MATCH = $MATCH{&#39;Identifier&#39;} })


    &lt;rule: NumList&gt;
      # Numbers in square brackets...
        \[
            ( \d+ (?: , \d+)* )
        \]

      # Return only the numbers...
        (?{ $MATCH = $CAPTURE })


    &lt;token: Cmd&gt;
      # Match standard variants then standardize the keyword...
        (?: mv | move | rename )      (?{ $MATCH = &#39;mv&#39;; })</code></pre>

<h2 id="Parse-time-data-processing"><a id="Parse"></a>Parse-time data processing</h2>

<p>Using code blocks in rules, it&#39;s often possible to fully process data as you parse it. For example, the <code>&lt;sum&gt;</code> rule shown in the previous section might be part of a simple calculator, implemented entirely in a single grammar. Such a calculator might look like this:</p>

<pre><code>    my $calculator = do{
        use Regexp::Grammars;
        qr{
            &lt;Answer&gt;

            &lt;rule: Answer&gt;
                ( &lt;.Mult&gt;+ % &lt;.Op=([+-])&gt; )
                    &lt;MATCH= (?{ eval $CAPTURE })&gt;

            &lt;rule: Mult&gt;
                ( &lt;.Pow&gt;+ % &lt;.Op=([*/%])&gt; )
                    &lt;MATCH= (?{ eval $CAPTURE })&gt;

            &lt;rule: Pow&gt;
                &lt;X=Term&gt; \^ &lt;Y=Pow&gt;
                    &lt;MATCH= (?{ $MATCH{X} ** $MATCH{Y}; })&gt;
              |
                    &lt;MATCH=Term&gt;

            &lt;rule: Term&gt;
                    &lt;MATCH=Literal&gt;
              | \(  &lt;MATCH=Answer&gt;  \)

            &lt;token: Literal&gt;
                    &lt;MATCH= ( [+-]? \d++ (?: \. \d++ )?+ )&gt;
        }xms
    };

    while (my $input = &lt;&gt;) {
        if ($input =~ $calculator) {
            say &quot;--&gt; $/{Answer}&quot;;
        }
    }</code></pre>

<p>Because every rule computes a value using the results of the subrules below it, and aliases that result to its <code>MATCH</code>, each rule returns a complete evaluation of the subexpression it matches, passing that back to higher-level rules, which then do the same.</p>

<p>Hence, the result returned to the very top-level rule (i.e. to <code>&lt;Answer&gt;</code>) is the complete evaluation of the entire expression that was matched. That means that, in the very process of having matched a valid expression, the calculator has also computed the value of that expression, which can then simply be printed directly.</p>

<p>It is often possible to have a grammar fully (or sometimes at least partially) evaluate or transform the data it is parsing, and this usually leads to very efficient and easy-to-maintain implementations.</p>

<p>The main limitation of this technique is that the data has to be in a well-structured form, where subsets of the data can be evaluated using only local information. In cases where the meaning of the data is distributed through that data non-hierarchically, or relies on global state, or on external information, it is often better to have the grammar simply construct a complete syntax tree for the data first, and then evaluate that syntax tree separately, after parsing is complete. The following section describes a feature of Regexp::Grammars that can make this second style of data processing simpler and more maintainable.</p>

<h2 id="Object-oriented-parsing"><a id="Object"></a>Object-oriented parsing</h2>

<p>When a grammar has parsed successfully, the <code>%/</code> variable will contain a series of nested hashes (and possibly arrays) representing the hierarchical structure of the parsed data.</p>

<p>Typically, the next step is to walk that tree, extracting or converting or otherwise processing that information. If the tree has nodes of many different types, it can be difficult to build a recursive subroutine that can navigate it easily.</p>

<p>A much cleaner solution is possible if the nodes of the tree are proper objects. In that case, you just define a <code>process()</code> or <code>traverse()</code> method for eah of the classes, and have every node call that method on each of its children. For example, if the parser were to return a tree of nodes representing the contents of a LaTeX file, then you could define the following methods:</p>

<pre><code>    sub Latex::file::explain
    {
        my ($self, $level) = @_;
        for my $element (@{$self-&gt;{element}}) {
            $element-&gt;explain($level);
        }
    }

    sub Latex::element::explain {
        my ($self, $level) = @_;
        (  $self-&gt;{command} || $self-&gt;{literal})-&gt;explain($level)
    }

    sub Latex::command::explain {
        my ($self, $level) = @_;
        say &quot;\t&quot;x$level, &quot;Command:&quot;;
        say &quot;\t&quot;x($level+1), &quot;Name: $self-&gt;{name}&quot;;
        if ($self-&gt;{options}) {
            say &quot;\t&quot;x$level, &quot;\tOptions:&quot;;
            $self-&gt;{options}-&gt;explain($level+2)
        }

        for my $arg (@{$self-&gt;{arg}}) {
            say &quot;\t&quot;x$level, &quot;\tArg:&quot;;
            $arg-&gt;explain($level+2)
        }
    }

    sub Latex::options::explain {
        my ($self, $level) = @_;
        $_-&gt;explain($level) foreach @{$self-&gt;{option}};
    }

    sub Latex::literal::explain {
        my ($self, $level, $label) = @_;
        $label //= &#39;Literal&#39;;
        say &quot;\t&quot;x$level, &quot;$label: &quot;, $self-&gt;{q{}};
    }</code></pre>

<p>and then simply write:</p>

<pre><code>    if ($text =~ $LaTeX_parser) {
        $/{LaTeX_file}-&gt;explain();
    }</code></pre>

<p>and the chain of <code>explain()</code> calls would cascade down the nodes of the tree, each one invoking the appropriate <code>explain()</code> method according to the type of node encountered.</p>

<p>The only problem is that, by default, Regexp::Grammars returns a tree of plain-old hashes, not LaTeX::Whatever objects. Fortunately, it&#39;s easy to request that the result hashes be automatically blessed into the appropriate classes, using the <code>&lt;objrule:...&gt;</code> and <code>&lt;objtoken:...&gt;</code> directives.</p>

<p>These directives are identical to the <code>&lt;rule:...&gt;</code> and <code>&lt;token:...&gt;</code> directives (respectively), except that the rule or token they create will also convert the hash it normally returns into an object of a specified class. This conversion is done by passing the result hash to the class&#39;s constructor:</p>

<pre><code>    $class-&gt;new(\%result_hash)</code></pre>

<p>if the class has a constructor method named <code>new()</code>, or else (if the class doesn&#39;t provide a constructor) by directly blessing the result hash:</p>

<pre><code>    bless \%result_hash, $class</code></pre>

<p>Note that, even if object is constructed via its own constructor, the module still expects the new object to be hash-based, and will fail if the object is anything but a blessed hash. The module issues an error in this case.</p>

<p>The generic syntax for these types of rules and tokens is:</p>

<pre><code>    &lt;objrule:  CLASS::NAME = RULENAME  &gt;
    &lt;objtoken: CLASS::NAME = TOKENNAME &gt;</code></pre>

<p>For example:</p>

<pre><code>    &lt;objrule: LaTeX::Element=component&gt;
        # ...Defines a rule that can be called as &lt;component&gt;
        # ...and which returns a hash-based LaTeX::Element object

    &lt;objtoken: LaTex::Literal=atom&gt;
        # ...Defines a token that can be called as &lt;atom&gt;
        # ...and which returns a hash-based LaTeX::Literal object</code></pre>

<p>Note that, just as in <a href="./Regexp::Grammars.html#Renaming-subrule-results">aliased subrule calls</a>, the name by which something is referred to outside the grammar (in this case, the class name) comes <i>before</i> the <code>=</code>, whereas the name that it is referred to inside the grammar comes <i>after</i> the <code>=</code>.</p>

<p>You can freely mix object-returning and plain-old-hash-returning rules and tokens within a single grammar, though you have to be careful not to subsequently try to call a method on any of the unblessed nodes.</p>

<h4 id="An-important-caveat-regarding-OO-rules"><a id="An"></a>An important caveat regarding OO rules</h4>

<p>Prior to Perl 5.14.0, Perl&#39;s regex engine was not fully re-entrant. This means that in older versions of Perl, it is not possible to re-invoke the regex engine when already inside the regex engine.</p>

<p>This means that you need to be careful that the <code>new()</code> constructors that are called by your object-rules do not themselves use regexes in any way, unless you&#39;re running under Perl 5.14 or later (in which case you can ignore what follows).</p>

<p>The two ways this is most likely to happen are:</p>

<ol>

<li><p>If you&#39;re using a class built on Moose, where one or more of the <code>has</code> uses a type constraint (such as <code>&#39;Int&#39;</code>) that is implemented via regex matching. For example:</p>

<pre><code>    has &#39;id&#39; =&gt; (is =&gt; &#39;rw&#39;, isa =&gt; &#39;Int&#39;);</code></pre>

<p>The workaround (for pre-5.14 Perls) is to replace the type constraint with one that doesn&#39;t use a regex. For example:</p>

<pre><code>    has &#39;id&#39; =&gt; (is =&gt; &#39;rw&#39;, isa =&gt; &#39;Num&#39;);</code></pre>

<p>Alternatively, you could define your own type constraint that avoids regexes:</p>

<pre><code>    use Moose::Util::TypeConstraints;

    subtype &#39;Non::Regex::Int&#39;,
         as &#39;Num&#39;,
      where { int($_) == $_ };

    no Moose::Util::TypeConstraints;

    # and later...

    has &#39;id&#39; =&gt; (is =&gt; &#39;rw&#39;, isa =&gt; &#39;Non::Regex::Int&#39;);</code></pre>

</li>
<li><p>If your class uses an <code>AUTOLOAD()</code> method to implement its constructor and that method uses the typical:</p>

<pre><code>    $AUTOLOAD =~ s/.*://;</code></pre>

<p>technique. The workaround here is to achieve the same effect without a regex. For example:</p>

<pre><code>    my $last_colon_pos = rindex($AUTOLOAD, &#39;:&#39;);
    substr $AUTOLOAD, 0, $last_colon_pos+1, q{};</code></pre>

</li>
</ol>

<p>Note that this caveat against using nested regexes also applies to any code blocks executed inside a rule or token (whether or not those rules or tokens are object-oriented).</p>

<h3 id="A-naming-shortcut"><a id="A"></a>A naming shortcut</h3>

<p>If an <code>&lt;objrule:...&gt;</code> or <code>&lt;objtoken:...&gt;</code> is defined with a class name that is <i>not</i> followed by <code>=</code> and a rule name, then the rule name is determined automatically from the classname. Specifically, the final component of the classname (i.e. after the last <code>::</code>, if any) is used.</p>

<p>For example:</p>

<pre><code>    &lt;objrule: LaTeX::Element&gt;
        # ...Defines a rule that can be called as &lt;Element&gt;
        # ...and which returns a hash-based LaTeX::Element object

    &lt;objtoken: LaTex::Literal&gt;
        # ...Defines a token that can be called as &lt;Literal&gt;
        # ...and which returns a hash-based LaTeX::Literal object

    &lt;objtoken: Comment&gt;
        # ...Defines a token that can be called as &lt;Comment&gt;
        # ...and which returns a hash-based Comment object</code></pre>

<h1 id="Debugging1">Debugging</h1>

<p>Regexp::Grammars provides a number of features specifically designed to help debug both grammars and the data they parse.</p>

<p>All debugging messages are written to a log file (which, by default, is just STDERR). However, you can specify a disk file explicitly by placing a <code>&lt;logfile:...&gt;</code> directive at the start of your grammar:</p>

<pre><code>    $grammar = qr{

        &lt;logfile: LaTeX_parser_log &gt;

        \A &lt;LaTeX_file&gt; \Z    # Pattern to match

        &lt;rule: LaTeX_file&gt;
            # etc.
    }x;</code></pre>

<p>You can also explicitly specify that messages go to the terminal:</p>

<pre><code>        &lt;logfile: - &gt;</code></pre>

<h2 id="Debugging-grammar-creation-with-&lt;logfile:...&gt;"><a id="Debugging2"></a><a id="Debugging-grammar-creation-with--logfile"></a>Debugging grammar creation with <code>&lt;logfile:...&gt;</code></h2>

<p>Whenever a log file has been directly specified, Regexp::Grammars automatically does verbose static analysis of your grammar. That is, whenever it compiles a grammar containing an explicit <code>&lt;logfile:...&gt;</code> directive it logs a series of messages explaining how it has interpreted the various components of that grammar. For example, the following grammar:</p>

<pre><code>    &lt;logfile: parser_log &gt;

    &lt;cmd&gt;

    &lt;rule: cmd&gt;
        mv &lt;from=file&gt; &lt;to=file&gt;
      | cp &lt;source&gt; &lt;[file]&gt;  &lt;.comment&gt;?</code></pre>

<p>would produce the following analysis in the &#39;parser_log&#39; file:</p>

<pre><code>    info | Processing the main regex before any rule definitions
         |    |
         |    |...Treating &lt;cmd&gt; as:
         |    |      |  match the subrule &lt;cmd&gt;
         |    |       \ saving the match in $MATCH{&#39;cmd&#39;}
         |    |
         |     \___End of main regex
         |
    info | Defining a rule: &lt;cmd&gt;
         |    |...Returns: a hash
         |    |
         |    |...Treating &#39; mv &#39; as:
         |    |       \ normal Perl regex syntax
         |    |
         |    |...Treating &lt;from=file&gt; as:
         |    |      |  match the subrule &lt;file&gt;
         |    |       \ saving the match in $MATCH{&#39;from&#39;}
         |    |
         |    |...Treating &lt;to=file&gt; as:
         |    |      |  match the subrule &lt;file&gt;
         |    |       \ saving the match in $MATCH{&#39;to&#39;}
         |    |
         |    |...Treating &#39; | cp &#39; as:
         |    |       \ normal Perl regex syntax
         |    |
         |    |...Treating &lt;source&gt; as:
         |    |      |  match the subrule &lt;source&gt;
         |    |       \ saving the match in $MATCH{&#39;source&#39;}
         |    |
         |    |...Treating &lt;[file]&gt; as:
         |    |      |  match the subrule &lt;file&gt;
         |    |       \ appending the match to $MATCH{&#39;file&#39;}
         |    |
         |    |...Treating &lt;.comment&gt;? as:
         |    |      |  match the subrule &lt;comment&gt; if possible
         |    |       \ but don&#39;t save anything
         |    |
         |     \___End of rule definition</code></pre>

<p>This kind of static analysis is a useful starting point in debugging a miscreant grammar, because it enables you to see what you actually specified (as opposed to what you <i>thought</i> you&#39;d specified).</p>

<h2 id="Debugging-grammar-execution-with-&lt;debug:...&gt;"><a id="Debugging3"></a><a id="Debugging-grammar-execution-with--debug"></a>Debugging grammar execution with <code>&lt;debug:...&gt;</code></h2>

<p>Regexp::Grammars also provides a simple interactive debugger, with which you can observe the process of parsing and the data being collected in any result-hash.</p>

<p>To initiate debugging, place a <code>&lt;debug:...&gt;</code> directive anywhere in your grammar. When parsing reaches that directive the debugger will be activated, and the command specified in the directive immediately executed. The available commands are:</p>

<pre><code>    &lt;debug: on&gt;    - Enable debugging, stop when a rule matches
    &lt;debug: match&gt; - Enable debugging, stop when a rule matches
    &lt;debug: try&gt;   - Enable debugging, stop when a rule is tried
    &lt;debug: run&gt;   - Enable debugging, run until the match completes
    &lt;debug: same&gt;  - Continue debugging (or not) as currently
    &lt;debug: off&gt;   - Disable debugging and continue parsing silently

    &lt;debug: continue&gt; - Synonym for &lt;debug: run&gt;
    &lt;debug: step&gt;     - Synonym for &lt;debug: try&gt;</code></pre>

<p>These directives can be placed anywhere within a grammar and take effect when that point is reached in the parsing. Hence, adding a <code>&lt;debug:step&gt;</code> directive is very much like setting a breakpoint at that point in the grammar. Indeed, a common debugging strategy is to turn debugging on and off only around a suspect part of the grammar:</p>

<pre><code>    &lt;rule: tricky&gt;   # This is where we think the problem is...
        &lt;debug:step&gt;
        &lt;preamble&gt; &lt;text&gt; &lt;postscript&gt;
        &lt;debug:off&gt;</code></pre>

<p>Once the debugger is active, it steps through the parse, reporting rules that are tried, matches and failures, backtracking and restarts, and the parser&#39;s location within both the grammar and the text being matched. That report looks like this:</p>

<pre><code>    ===============&gt; Trying &lt;grammar&gt; from position 0
    &gt; cp file1 file2 |...Trying &lt;cmd&gt;
                     |   |...Trying &lt;cmd=(cp)&gt;
                     |   |    \FAIL &lt;cmd=(cp)&gt;
                     |    \FAIL &lt;cmd&gt;
                      \FAIL &lt;grammar&gt;
    ===============&gt; Trying &lt;grammar&gt; from position 1
     cp file1 file2  |...Trying &lt;cmd&gt;
                     |   |...Trying &lt;cmd=(cp)&gt;
     file1 file2     |   |    \_____&lt;cmd=(cp)&gt; matched &#39;cp&#39;
    file1 file2      |   |...Trying &lt;[file]&gt;+
     file2           |   |    \_____&lt;[file]&gt;+ matched &#39;file1&#39;
                     |   |...Trying &lt;[file]&gt;+
    [eos]            |   |    \_____&lt;[file]&gt;+ matched &#39; file2&#39;
                     |   |...Trying &lt;[file]&gt;+
                     |   |    \FAIL &lt;[file]&gt;+
                     |   |...Trying &lt;target&gt;
                     |   |   |...Trying &lt;file&gt;
                     |   |   |    \FAIL &lt;file&gt;
                     |   |    \FAIL &lt;target&gt;
     &lt;~~~~~~~~~~~~~~ |   |...Backtracking 5 chars and trying new match
    file2            |   |...Trying &lt;target&gt;
                     |   |   |...Trying &lt;file&gt;
                     |   |   |    \____ &lt;file&gt; matched &#39;file2&#39;
    [eos]            |   |    \_____&lt;target&gt; matched &#39;file2&#39;
                     |    \_____&lt;cmd&gt; matched &#39; cp file1 file2&#39;
                      \_____&lt;grammar&gt; matched &#39; cp file1 file2&#39;</code></pre>

<p>The first column indicates the point in the input at which the parser is trying to match, as well as any backtracking or forward searching it may need to do. The remainder of the columns track the parser&#39;s hierarchical traversal of the grammar, indicating which rules are tried, which succeed, and what they match.</p>

<p>Provided the logfile is a terminal (as it is by default), the debugger also pauses at various points in the parsing process--before trying a rule, after a rule succeeds, or at the end of the parse--according to the most recent command issued. When it pauses, you can issue a new command by entering a single letter:</p>

<pre><code>    m       - to continue until the next subrule matches
    t or s  - to continue until the next subrule is tried
    r or c  - to continue to the end of the grammar
    o       - to switch off debugging</code></pre>

<p>Note that these are the first letters of the corresponding <code>&lt;debug:...&gt;</code> commands, listed earlier. Just hitting ENTER while the debugger is paused repeats the previous command.</p>

<p>While the debugger is paused you can also type a &#39;d&#39;, which will display the result-hash for the current rule. This can be useful for detecting which rule isn&#39;t returning the data you expected.</p>

<h3 id="Resizing-the-context-string"><a id="Resizing"></a>Resizing the context string</h3>

<p>By default, the first column of the debugger output (which shows the current matching position within the string) is limited to a width of 20 columns.</p>

<p>However, you can change that limit calling the <code>Regexp::Grammars::set_context_width()</code> subroutine. You have to specify the fully qualified name, however, as Regexp::Grammars does not export this (or any other) subroutine.</p>

<p><code>set_context_width()</code> expects a single argument: a positive integer indicating the maximal allowable width for the context column. It issues a warning if an invalid value is passed, and ignores it.</p>

<p>If called in a void context, <code>set_context_width()</code> changes the context width permanently throughout your application. If called in a scalar or list context, <code>set_context_width()</code> returns an object whose destructor will cause the context width to revert to its previous value. This means you can temporarily change the context width within a given block with something like:</p>

<pre><code>    {
        my $temporary = Regexp::Grammars::set_context_width(50);

        if ($text =~ $parser) {
            do_stuff_with( %/ );
        }

    } # &lt;--- context width automagically reverts at this point</code></pre>

<p>and the context width will change back to its previous value when <code>$temporary</code> goes out of scope at the end of the block.</p>

<h2 id="User-defined-logging-with-&lt;log:...&gt;"><a id="User"></a><a id="User-defined-logging-with--log"></a>User-defined logging with <code>&lt;log:...&gt;</code></h2>

<p>Both static and interactive debugging send a series of predefined log messages to whatever log file you have specified. It is also possible to send additional, user-defined messages to the log, using the <code>&lt;log:...&gt;</code> directive.</p>

<p>This directive expects either a simple text or a codeblock as its single argument. If the argument is a code block, that code is expected to return the text of the message; if the argument is anything else, that something else <i>is</i> the literal message. For example:</p>

<pre><code>    &lt;rule: ListElem&gt;

        &lt;Elem=   ( [a-z]\d+) &gt;
            &lt;log: Checking for a suffix, too...&gt;

        &lt;Suffix= ( : \d+   ) &gt;?
            &lt;log: (?{ &quot;ListElem: $MATCH{Elem} and $MATCH{Suffix}&quot; })&gt;</code></pre>

<p>User-defined log messages implemented using a codeblock can also specify a severity level. If the codeblock of a <code>&lt;log:...&gt;</code> directive returns two or more values, the first is treated as a log message severity indicator, and the remaining values as separate lines of text to be logged. For example:</p>

<pre><code>    &lt;rule: ListElem&gt;
        &lt;Elem=   ( [a-z]\d+) &gt;
        &lt;Suffix= ( : \d+   ) &gt;?

            &lt;log: (?{
                warn =&gt; &quot;Elem was: $MATCH{Elem}&quot;,
                        &quot;Suffix was $MATCH{Suffix}&quot;,
            })&gt;</code></pre>

<p>When they are encountered, user-defined log messages are interspersed between any automatic log messages (i.e. from the debugger), at the correct level of nesting for the current rule.</p>

<h2 id="Debugging-non-grammars"><a id="Debugging4"></a>Debugging non-grammars</h2>

<p><i>[Note that, with the release in 2012 of the Regexp::Debugger module (on CPAN) the techniques described below are unnecessary. If you need to debug plain Perl regexes, use Regexp::Debugger instead.]</i></p>

<p>It is possible to use Regexp::Grammars without creating <i>any</i> subrule definitions, simply to debug a recalcitrant regex. For example, if the following regex wasn&#39;t working as expected:</p>

<pre><code>    my $balanced_brackets = qr{
        \(             # left delim
        (?:
            \\         # escape or
        |   (?R)       # recurse or
        |   .          # whatever
        )*
        \)             # right delim
    }xms;</code></pre>

<p>you could instrument it with aliased subpatterns and then debug it step-by-step, using Regexp::Grammars:</p>

<pre><code>    use Regexp::Grammars;

    my $balanced_brackets = qr{
        &lt;debug:step&gt;

        &lt;.left_delim=  (  \(  )&gt;
        (?:
            &lt;.escape=  (  \\  )&gt;
        |   &lt;.recurse= ( (?R) )&gt;
        |   &lt;.whatever=(  .   )&gt;
        )*
        &lt;.right_delim= (  \)  )&gt;
    }xms;

    while (&lt;&gt;) {
        say &#39;matched&#39; if /$balanced_brackets/;
    }</code></pre>

<p>Note the use of <a href="./Regexp::Grammars.html#Amnesiac-subrule-calls">amnesiac aliased subpatterns</a> to avoid needlessly building a result-hash. Alternatively, you could use listifying aliases to preserve the matching structure as an additional debugging aid:</p>

<pre><code>    use Regexp::Grammars;

    my $balanced_brackets = qr{
        &lt;debug:step&gt;

        &lt;[left_delim=  (  \(  )]&gt;
        (?:
            &lt;[escape=  (  \\  )]&gt;
        |   &lt;[recurse= ( (?R) )]&gt;
        |   &lt;[whatever=(  .   )]&gt;
        )*
        &lt;[right_delim= (  \)  )]&gt;
    }xms;

    if ( &#39;(a(bc)d)&#39; =~ /$balanced_brackets/) {
        use Data::Dumper &#39;Dumper&#39;;
        warn Dumper \%/;
    }</code></pre>

<h1 id="Handling-errors-when-parsing"><a id="Handling"></a>Handling errors when parsing</h1>

<p>Assuming you have correctly debugged your grammar, the next source of problems will probably be invalid input (especially if that input is being provided interactively). So Regexp::Grammars also provides some support for detecting when a parse is likely to fail...and informing the user why.</p>

<h2 id="Requirements">Requirements</h2>

<p>The <code>&lt;require:...&gt;</code> directive is useful for testing conditions that it&#39;s not easy (or even possible) to check within the syntax of the the regex itself. For example:</p>

<pre><code>    &lt;rule: IPV4_Octet_Decimal&gt;
        # Up three digits...
        &lt;MATCH= ( \d{1,3}+ )&gt;

        # ...but less than 256...
        &lt;require: (?{ $MATCH &lt;= 255 })&gt;</code></pre>

<p>A require expects a regex codeblock as its argument and succeeds if the final value of that codeblock is true. If the final value is false, the directive fails and the rule starts backtracking.</p>

<p>Note, in this example that the digits are matched with <code> \d{1,3}+ </code>. The trailing <code>+</code> prevents the <code>{1,3}</code> repetition from backtracking to a smaller number of digits if the <code>&lt;require:...&gt;</code> fails.</p>

<h2 id="Handling-failure"><a id="Handling1"></a>Handling failure</h2>

<p>The module has limited support for error reporting from within a grammar, in the form of the <code>&lt;error:...&gt;</code> and <code>&lt;warning:...&gt;</code> directives and their shortcuts: <code>&lt;...&gt;</code>, <code>&lt;!!!&gt;</code>, and <code>&lt;???&gt;</code></p>

<h3 id="Error-messages"><a id="Error"></a>Error messages</h3>

<p>The <code>&lt;error: MSG&gt;</code> directive queues a <i>conditional</i> error message within <code>@!</code> and then fails to match (that is, it is equivalent to a <code>(?!)</code> when matching). For example:</p>

<pre><code>    &lt;rule: ListElem&gt;
        &lt;SerialNumber&gt;
      | &lt;ClientName&gt;
      | &lt;error: (?{ $errcount++ . &#39;: Missing list element&#39; })&gt;</code></pre>

<p>So a common code pattern when using grammars that do this kind of error detection is:</p>

<pre><code>    if ($text =~ $grammar) {
        # Do something with the data collected in %/
    }
    else {
        say {*STDERR} $_ for @!;   # i.e. report all errors
    }</code></pre>

<p>Each error message is conditional in the sense that, if any surrounding rule subsequently matches, the message is automatically removed from <code>@!</code>. This implies that you can queue up as many error messages as you wish, but they will only remain in <code>@!</code> if the match ultimately fails. Moreover, only those error messages originating from rules that actually contributed to the eventual failure-to-match will remain in <code>@!</code>.</p>

<p>If a code block is specified as the argument, the error message is whatever final value is produced when the block is executed. Note that this final value does not have to be a string (though it does have to be a scalar).</p>

<pre><code>    &lt;rule: ListElem&gt;
        &lt;SerialNumber&gt;
      | &lt;ClientName&gt;
      | &lt;error: (?{
            # Return a hash, with the error information...
            { errnum =&gt; $errcount++, msg =&gt; &#39;Missing list element&#39; }
        })&gt;</code></pre>

<p>If anything else is specified as the argument, it is treated as a literal error string (and may not contain an unbalanced <code>&#39;&lt;&#39;</code> or <code>&#39;&gt;&#39;</code>, nor any interpolated variables).</p>

<p>However, if the literal error string begins with &quot;Expected &quot; or &quot;Expecting &quot;, then the error string automatically has the following &quot;context suffix&quot; appended:</p>

<pre><code>    , but found &#39;$CONTEXT&#39; instead</code></pre>

<p>For example:</p>

<pre><code>    qr{ &lt;Arithmetic_Expression&gt;                # ...Match arithmetic expression
      |                                        # Or else
        &lt;error: Expected a valid expression&gt;   # ...Report error, and fail

        # Rule definitions here...
    }xms;</code></pre>

<p>On an invalid input this example might produce an error message like:</p>

<pre><code>    &quot;Expected a valid expression, but found &#39;(2+3]*7/&#39; instead&quot;</code></pre>

<p>The value of the special $CONTEXT variable is found by looking ahead in the string being matched against, to locate the next sequence of non-blank characters after the current parsing position. This variable may also be explicitly used within the <code>&lt;error: (?{...})&gt;</code> form of the directive.</p>

<p>As a special case, if you omit the message entirely from the directive, it is supplied automatically, derived from the name of the current rule. For example, if the following rule were to fail to match:</p>

<pre><code>    &lt;rule: Arithmetic_expression&gt;
          &lt;Multiplicative_Expression&gt;+ % ([+-])
        | &lt;error:&gt;</code></pre>

<p>the error message queued would be:</p>

<pre><code>    &quot;Expected arithmetic expression, but found &#39;one plus two&#39; instead&quot;</code></pre>

<p>Note however, that it is still essential to include the colon in the directive. A common mistake is to write:</p>

<pre><code>    &lt;rule: Arithmetic_expression&gt;
          &lt;Multiplicative_Expression&gt;+ % ([+-])
        | &lt;error&gt;</code></pre>

<p>which merely attempts to call <code>&lt;rule: error&gt;</code> if the first alternative fails.</p>

<h3 id="Warning-messages"><a id="Warning"></a>Warning messages</h3>

<p>Sometimes, you want to detect problems, but not invalidate the entire parse as a result. For those occasions, the module provides a &quot;less stringent&quot; form of error reporting: the <code>&lt;warning:...&gt;</code> directive.</p>

<p>This directive is exactly the same as an <code>&lt;error:...&gt;</code> in every respect except that it does not induce a failure to match at the point it appears.</p>

<p>The directive is, therefore, useful for reporting <i>non-fatal</i> problems in a parse. For example:</p>

<pre><code>    qr{ \A            # ...Match only at start of input
        &lt;ArithExpr&gt;   # ...Match a valid arithmetic expression

        (?:
            # Should be at end of input...
            \s* \Z
          |
            # If not, report the fact but don&#39;t fail...
            &lt;warning: Expected end-of-input&gt;
            &lt;warning: (?{ &quot;Extra junk at index $INDEX: $CONTEXT&quot; })&gt;
        )

        # Rule definitions here...
    }xms;</code></pre>

<p>Note that, because they do not induce failure, two or more <code>&lt;warning:...&gt;</code> directives can be &quot;stacked&quot; in sequence, as in the previous example.</p>

<h3 id="Stubbing">Stubbing</h3>

<p>The module also provides three useful shortcuts, specifically to make it easy to declare, but not define, rules and tokens.</p>

<p>The <code>&lt;...&gt;</code> and <code>&lt;!!!&gt;</code> directives are equivalent to the directive:</p>

<pre><code>    &lt;error: Cannot match RULENAME (not implemented)&gt;</code></pre>

<p>The <code>&lt;???&gt;</code> is equivalent to the directive:</p>

<pre><code>    &lt;warning: Cannot match RULENAME (not implemented)&gt;</code></pre>

<p>For example, in the following grammar:</p>

<pre><code>    &lt;grammar: List::Generic&gt;

    &lt;rule: List&gt;
        &lt;[Item]&gt;+ % (\s*,\s*)

    &lt;rule: Item&gt;
        &lt;...&gt;</code></pre>

<p>the <code>Item</code> rule is declared but not defined. That means the grammar will compile correctly, (the <code>List</code> rule won&#39;t complain about a call to a non-existent <code>Item</code>), but if the <code>Item</code> rule isn&#39;t overridden in some derived grammar, a match-time error will occur when <code>List</code> tries to match the <code>&lt;...&gt;</code> within <code>Item</code>.</p>

<h3 id="Localizing-the-(semi-)automatic-error-messages"><a id="Localizing"></a><a id="Localizing-the--semi--automatic-error-messages"></a>Localizing the (semi-)automatic error messages</h3>

<p>Error directives of any of the following forms:</p>

<pre><code>    &lt;error: Expecting identifier&gt;

    &lt;error: &gt;

    &lt;...&gt;

    &lt;!!!&gt;</code></pre>

<p>or their warning equivalents:</p>

<pre><code>    &lt;warning: Expecting identifier&gt;

    &lt;warning: &gt;

    &lt;???&gt;</code></pre>

<p>each autogenerate part or all of the actual error message they produce. By default, that autogenerated message is always produced in English.</p>

<p>However, the module provides a mechanism by which you can intercept <i>every</i> error or warning that is queued to <code>@!</code> via these directives...and localize those messages.</p>

<p>To do this, you call <code>Regexp::Grammars::set_error_translator()</code> (with the full qualification, since Regexp::Grammars does not export it...nor anything else, for that matter).</p>

<p>The <code>set_error_translator()</code> subroutine expect as single argument, which must be a reference to another subroutine. This subroutine is then called whenever an error or warning message is queued to <code>@!</code>.</p>

<p>The subroutine is passed three arguments:</p>

<ul>

<li><p>the message string,</p>

</li>
<li><p>the name of the rule from which the error or warning was queued, and</p>

</li>
<li><p>the value of <code>$CONTEXT</code> when the error or warning was encountered</p>

</li>
</ul>

<p>The subroutine is expected to return the final version of the message that is actually to be appended to <code>@!</code>. To accomplish this it may make use of one of the many internationalization/localization modules available in Perl, or it may do the conversion entirely by itself.</p>

<p>The first argument is always exactly what appeared as a message in the original directive (regardless of whether that message is supposed to trigger autogeneration, or is just a &quot;regular&quot; error message). That is:</p>

<pre><code>    Directive                         1st argument

    &lt;error: Expecting identifier&gt;     &quot;Expecting identifier&quot;
    &lt;warning: That&#39;s not a moon!&gt;     &quot;That&#39;s not a moon!&quot;
    &lt;error: &gt;                         &quot;&quot;
    &lt;warning: &gt;                       &quot;&quot;
    &lt;...&gt;                             &quot;&quot;
    &lt;!!!&gt;                             &quot;&quot;
    &lt;???&gt;                             &quot;&quot;</code></pre>

<p>The second argument always contains the name of the rule in which the directive was encountered. For example, when invoked from within <code>&lt;rule: Frinstance&gt;</code> the following directives produce:</p>

<pre><code>    Directive                         2nd argument

    &lt;error: Expecting identifier&gt;     &quot;Frinstance&quot;
    &lt;warning: That&#39;s not a moon!&gt;     &quot;Frinstance&quot;
    &lt;error: &gt;                         &quot;Frinstance&quot;
    &lt;warning: &gt;                       &quot;Frinstance&quot;
    &lt;...&gt;                             &quot;-Frinstance&quot;
    &lt;!!!&gt;                             &quot;-Frinstance&quot;
    &lt;???&gt;                             &quot;-Frinstance&quot;</code></pre>

<p>Note that the &quot;unimplemented&quot; markers pass the rule name with a preceding <code>&#39;-&#39;</code>. This allows your translator to distinguish between &quot;empty&quot; messages (which should then be generated automatically) and the &quot;unimplemented&quot; markers (which should report that the rule is not yet properly defined).</p>

<p>If you call <code>Regexp::Grammars::set_error_translator()</code> in a void context, the error translator is permanently replaced (at least, until the next call to <code>set_error_translator()</code>).</p>

<p>However, if you call <code>Regexp::Grammars::set_error_translator()</code> in a scalar or list context, it returns an object whose destructor will restore the previous translator. This allows you to install a translator only within a given scope, like so:</p>

<pre><code>    {
        my $temporary
            = Regexp::Grammars::set_error_translator(\&amp;my_translator);

        if ($text =~ $parser) {
            do_stuff_with( %/ );
        }
        else {
            report_errors_in( @! );
        }

    } # &lt;--- error translator automagically reverts at this point</code></pre>

<p><b>Warning</b>: any error translation subroutine you install will be called during the grammar&#39;s parsing phase (i.e. as the grammar&#39;s regex is matching). You should therefore ensure that your translator does not itself use regular expressions, as nested evaluations of regexes inside other regexes are extremely problematical (i.e. almost always disastrous) in Perl.</p>

<h2 id="Restricting-how-long-a-parse-runs"><a id="Restricting"></a>Restricting how long a parse runs</h2>

<p>Like the core Perl 5 regex engine on which they are built, the grammars implemented by Regexp::Grammars are essentially top-down parsers. This means that they may occasionally require an exponentially long time to parse a particular input. This usually occurs if a particular grammar includes a lot of recursion or nested backtracking, especially if the grammar is then matched against a long string.</p>

<p>The judicious use of non-backtracking repetitions (i.e. <code>x*+</code> and <code>x++</code>) can significantly improve parsing performance in many such cases. Likewise, carefully reordering any high-level alternatives (so as to test simple common cases first) can substantially reduce parsing times.</p>

<p>However, some languages are just intrinsically slow to parse using top-down techniques (or, at least, may have slow-to-parse corner cases).</p>

<p>To help cope with this constraint, Regexp::Grammars provides a mechanism by which you can limit the total effort that a given grammar will expend in attempting to match. The <code>&lt;timeout:...&gt;</code> directive allows you to specify how long a grammar is allowed to continue trying to match before giving up. It expects a single argument, which must be an unsigned integer, and it treats this integer as the number of seconds to continue attempting to match.</p>

<p>For example:</p>

<pre><code>    &lt;timeout: 10&gt;    # Give up after 10 seconds</code></pre>

<p>indicates that the grammar should keep attempting to match for another 10 seconds from the point where the directive is encountered during a parse. If the complete grammar has not matched in that time, the entire match is considered to have failed, the matching process is immediately terminated, and a standard error message (<code>&#39;Internal error: Timed out after 10 seconds (as requested)&#39;</code>) is returned in <code>@!</code>.</p>

<p>A <code>&lt;timeout:...&gt;</code> directive can be placed anywhere in a grammar, but is most usually placed at the very start, so that the entire grammar is governed by the specified time limit. The second most common alternative is to place the timeout at the start of a particular subrule that is known to be potentially very slow.</p>

<p>A common mistake is to put the timeout specification at the top level of the grammar, but place it <i>after</i> the actual subrule to be matched, like so:</p>

<pre><code>    my $grammar = qr{

        &lt;Text_Corpus&gt;      # Subrule to be matched
        &lt;timeout: 10&gt;      # Useless use of timeout

        &lt;rule: Text_Corpus&gt;
            # et cetera...
    }xms;</code></pre>

<p>Since the parser will only reach the <code>&lt;timeout: 10&gt;</code> directive <i>after</i> it has completely matched <code>&lt;Text_Corpus&gt;</code>, the timeout is only initiated at the very end of the matching process and so does not limit that process in any useful way.</p>

<h3 id="Immediate-timeouts"><a id="Immediate"></a>Immediate timeouts</h3>

<p>As you might expect, a <code>&lt;timeout: 0&gt;</code> directive tells the parser to keep trying for only zero more seconds, and therefore will immediately cause the entire surrounding grammar to fail (no matter how deeply within that grammar the directive is encountered).</p>

<p>This can occasionally be exteremely useful. If you know that detecting a particular datum means that the grammar will never match, no matter how many other alternatives may subsequently be tried, you can short-circuit the parser by injecting a <code>&lt;timeout: 0&gt;</code> immediately after the offending datum is detected.</p>

<p>For example, if your grammar only accepts certain versions of the language being parsed, you could write:</p>

<pre><code>    &lt;rule: Valid_Language_Version&gt;
            vers = &lt;%AcceptableVersions&gt;
        |
            vers = &lt;bad_version=(\S++)&gt;
            &lt;warning: (?{ &quot;Cannot parse language version $MATCH{bad_version}&quot; })&gt;
            &lt;timeout: 0&gt;</code></pre>

<p>In fact, this <code>&lt;warning: MSG&gt; &lt;timeout: 0&gt;</code> sequence is sufficiently useful, sufficiently complex, and sufficiently easy to get wrong, that Regexp::Grammars provides a handy shortcut for it: the <code>&lt;fatal:...&gt;</code> directive. A <code>&lt;fatal:...&gt;</code> is exactly equivalent to a <code>&lt;warning:...&gt;</code> followed by a zero-timeout, so the previous example could also be written:</p>

<pre><code>    &lt;rule: Valid_Language_Version&gt;
            vers = &lt;%AcceptableVersions&gt;
        |
            vers = &lt;bad_version=(\S++)&gt;
            &lt;fatal: (?{ &quot;Cannot parse language version $MATCH{bad_version}&quot; })&gt;</code></pre>

<p>Like <code>&lt;error:...&gt;</code> and <code>&lt;warning:...&gt;</code>, <code>&lt;fatal:...&gt;</code> also provides its own failure context in <code>$CONTEXT</code>, so the previous example could be further simplified to:</p>

<pre><code>    &lt;rule: Valid_Language_Version&gt;
            vers = &lt;%AcceptableVersions&gt;
        |
            vers = &lt;fatal:(?{ &quot;Cannot parse language version $CONTEXT&quot; })&gt;</code></pre>

<p>Also like <code>&lt;error:...&gt;</code>, <code>&lt;fatal:...&gt;</code> can autogenerate an error message if none is provided, so the example could be still further reduced to:</p>

<pre><code>    &lt;rule: Valid_Language_Version&gt;
            vers = &lt;%AcceptableVersions&gt;
        |
            vers = &lt;fatal:&gt;</code></pre>

<p>In this last case, however, the error message returned in <code>@!</code> would no longer be:</p>

<pre><code>    Cannot parse language version 0.95</code></pre>

<p>It would now be:</p>

<pre><code>    Expected valid language version, but found &#39;0.95&#39; instead</code></pre>

<h1 id="Scoping-considerations"><a id="Scoping"></a>Scoping considerations</h1>

<p>If you intend to use a grammar as part of a larger program that contains other (non-grammatical) regexes, it is more efficient--and less error-prone--to avoid having Regexp::Grammars process those regexes as well. So it&#39;s often a good idea to declare your grammar in a <code>do</code> block, thereby restricting the scope of the module&#39;s effects.</p>

<p>For example:</p>

<pre><code>    my $grammar = do {
        use Regexp::Grammars;
        qr{
            &lt;file&gt;

            &lt;rule: file&gt;
                &lt;prelude&gt;
                &lt;data&gt;
                &lt;postlude&gt;

            &lt;rule: prelude&gt;
                # etc.
        }x;
    };</code></pre>

<p>Because the effects of Regexp::Grammars are lexically scoped, any regexes defined outside that <code>do</code> block will be unaffected by the module.</p>

<h1 id="INTERFACE">INTERFACE</h1>

<h2 id="Perl-API"><a id="Perl"></a>Perl API</h2>

<dl>

<dt id="use-Regexp::Grammars;"><a id="use"></a><a id="use-Regexp::Grammars"></a><code>use Regexp::Grammars;</code></dt>
<dd>

<p>Causes all regexes in the current lexical scope to be compile-time processed for grammar elements.</p>

</dd>
<dt id="$str-=~-$grammar"><a id="str----grammar"></a><code>$str =~ $grammar</code></dt>
<dd>

</dd>
<dt id="$str-=~-/$grammar/"><a id="str----grammar1"></a><code>$str =~ /$grammar/</code></dt>
<dd>

<p>Attempt to match the grammar against the string, building a nested data structure from it.</p>

</dd>
<dt id="%/"><a id="pod"></a><code>%/</code></dt>
<dd>

<p>This hash is assigned the nested data structure created by any successful match of a grammar regex.</p>

</dd>
<dt id="@!"><a id="pod1"></a><code>@!</code></dt>
<dd>

<p>This array is assigned the queue of error messages created by any unsuccessful match attempt of a grammar regex.</p>

</dd>
</dl>

<h2 id="Grammar-syntax"><a id="Grammar"></a>Grammar syntax</h2>

<h3 id="Directives1">Directives</h3>

<dl>

<dt id="&lt;rule:-IDENTIFIER&gt;"><a id="rule:-IDENTIFIER"></a><code>&lt;rule: IDENTIFIER&gt;</code></dt>
<dd>

<p>Define a rule whose name is specified by the supplied identifier.</p>

<p>Everything following the <code>&lt;rule:...&gt;</code> directive (up to the next <code>&lt;rule:...&gt;</code> or <code>&lt;token:...&gt;</code> directive) is treated as part of the rule being defined.</p>

<p>Any whitespace in the rule is replaced by a call to the <code>&lt;.ws&gt;</code> subrule (which defaults to matching <code>\s*</code>, but may be explicitly redefined).</p>

</dd>
<dt id="&lt;token:-IDENTIFIER&gt;"><a id="token:-IDENTIFIER"></a><code>&lt;token: IDENTIFIER&gt;</code></dt>
<dd>

<p>Define a rule whose name is specified by the supplied identifier.</p>

<p>Everything following the <code>&lt;token:...&gt;</code> directive (up to the next <code>&lt;rule:...&gt;</code> or <code>&lt;token:...&gt;</code> directive) is treated as part of the rule being defined.</p>

<p>Any whitespace in the rule is ignored (under the <code>/x</code> modifier), or explicitly matched (if <code>/x</code> is not used).</p>

</dd>
<dt id="&lt;objrule:-IDENTIFIER&gt;"><a id="objrule:-IDENTIFIER"></a><code>&lt;objrule: IDENTIFIER&gt;</code></dt>
<dd>

</dd>
<dt id="&lt;objtoken:-IDENTIFIER&gt;"><a id="objtoken:-IDENTIFIER"></a><code>&lt;objtoken: IDENTIFIER&gt;</code></dt>
<dd>

<p>Identical to a <code>&lt;rule: IDENTIFIER&gt;</code> or <code>&lt;token: IDENTIFIER&gt;</code> declaration, except that the rule or token will also bless the hash it normally returns, converting it to an object of a class whose name is the same as the rule or token itself.</p>

</dd>
<dt id="&lt;require:-(?{-CODE-})-&gt;"><a id="require:---CODE"></a><code>&lt;require: (?{ CODE }) &gt;</code></dt>
<dd>

<p>The code block is executed and if its final value is true, matching continues from the same position. If the block&#39;s final value is false, the match fails at that point and starts backtracking.</p>

</dd>
<dt id="&lt;error:-(?{-CODE-})-&gt;"><a id="error:---CODE"></a><code>&lt;error: (?{ CODE }) &gt;</code></dt>
<dd>

</dd>
<dt id="&lt;error:-LITERAL-TEXT-&gt;"><a id="error:-LITERAL-TEXT"></a><code>&lt;error: LITERAL TEXT &gt;</code></dt>
<dd>

</dd>
<dt id="&lt;error:-&gt;"><a id="error"></a><code>&lt;error: &gt;</code></dt>
<dd>

<p>This directive queues a <i>conditional</i> error message within the global special variable <code>@!</code> and then fails to match at that point (that is, it is equivalent to a <code>(?!)</code> or <code>(*FAIL)</code> when matching).</p>

</dd>
<dt id="&lt;fatal:-(?{-CODE-})-&gt;"><a id="fatal:---CODE"></a><code>&lt;fatal: (?{ CODE }) &gt;</code></dt>
<dd>

</dd>
<dt id="&lt;fatal:-LITERAL-TEXT-&gt;"><a id="fatal:-LITERAL-TEXT"></a><code>&lt;fatal: LITERAL TEXT &gt;</code></dt>
<dd>

</dd>
<dt id="&lt;fatal:-&gt;"><a id="fatal"></a><code>&lt;fatal: &gt;</code></dt>
<dd>

<p>This directive is exactly the same as an <code>&lt;error:...&gt;</code> in every respect except that it immediately causes the entire surrounding grammar to fail, and parsing to immediate cease.</p>

</dd>
<dt id="&lt;warning:-(?{-CODE-})-&gt;"><a id="warning:---CODE"></a><code>&lt;warning: (?{ CODE }) &gt;</code></dt>
<dd>

</dd>
<dt id="&lt;warning:-LITERAL-TEXT-&gt;"><a id="warning:-LITERAL-TEXT"></a><code>&lt;warning: LITERAL TEXT &gt;</code></dt>
<dd>

<p>This directive is exactly the same as an <code>&lt;error:...&gt;</code> in every respect except that it does not induce a failure to match at the point it appears. That is, it is equivalent to a <code>(?=)</code> [&quot;succeed and continue matching&quot;], rather than a <code>(?!)</code> [&quot;fail and backtrack&quot;].</p>

</dd>
<dt id="&lt;debug:-COMMAND-&gt;"><a id="debug:-COMMAND"></a><code>&lt;debug: COMMAND &gt;</code></dt>
<dd>

<p>During the matching of grammar regexes send debugging and warning information to the specified log file (see <code>&lt;logfile: LOGFILE&gt;</code>).</p>

<p>The available <code>COMMAND</code>&#39;s are:</p>

<pre><code>    &lt;debug: continue&gt;    ___ Debug until end of complete parse
    &lt;debug: run&gt;         _/

    &lt;debug: on&gt;          ___ Debug until next subrule match
    &lt;debug: match&gt;       _/

    &lt;debug: try&gt;         ___ Debug until next subrule call or match
    &lt;debug: step&gt;        _/

    &lt;debug: same&gt;        ___ Maintain current debugging mode

    &lt;debug: off&gt;         ___ No debugging</code></pre>

<p>See also the <code>$DEBUG</code> special variable.</p>

</dd>
<dt id="&lt;logfile:-LOGFILE&gt;"><a id="logfile:-LOGFILE"></a><code>&lt;logfile: LOGFILE&gt;</code></dt>
<dd>

</dd>
<dt id="&lt;logfile:-&gt;"><a id="logfile"></a><code>&lt;logfile: - &gt;</code></dt>
<dd>

<p>During the compilation of grammar regexes, send debugging and warning information to the specified LOGFILE (or to <code>*STDERR</code> if <code>-</code> is specified).</p>

<p>If the specified LOGFILE name contains a <code>%t</code>, it is replaced with a (sortable) &quot;YYYYMMDD.HHMMSS&quot; timestamp. For example:</p>

<pre><code>    &lt;logfile: test-run-%t &gt;</code></pre>

<p>executed at around 9.30pm on the 21st of March 2009, would generate a log file named: <code>test-run-20090321.213056</code></p>

</dd>
<dt id="&lt;log:-(?{-CODE-})-&gt;"><a id="log:---CODE"></a><code>&lt;log: (?{ CODE }) &gt;</code></dt>
<dd>

</dd>
<dt id="&lt;log:-LITERAL-TEXT-&gt;"><a id="log:-LITERAL-TEXT"></a><code>&lt;log: LITERAL TEXT &gt;</code></dt>
<dd>

<p>Append a message to the log file. If the argument is a code block, that code is expected to return the text of the message; if the argument is anything else, that something else <i>is</i> the literal message.</p>

<p>If the block returns two or more values, the first is treated as a log message severity indicator, and the remaining values as separate lines of text to be logged.</p>

</dd>
<dt id="&lt;timeout:-INT-&gt;"><a id="timeout:-INT"></a><code>&lt;timeout: INT &gt;</code></dt>
<dd>

<p>Restrict the match-time of the parse to the specified number of seconds. Queues a error message and terminates the entire match process if the parse does not complete within the nominated time limit.</p>

</dd>
</dl>

<h3 id="Subrule-calls"><a id="Subrule1"></a>Subrule calls</h3>

<dl>

<dt id="&lt;IDENTIFIER&gt;"><a id="IDENTIFIER"></a><code>&lt;IDENTIFIER&gt;</code></dt>
<dd>

<p>Call the subrule whose name is IDENTIFIER.</p>

<p>If it matches successfully, save the hash it returns in the current scope&#39;s result-hash, under the key <code>&#39;IDENTIFIER&#39;</code>.</p>

</dd>
<dt id="&lt;IDENTIFIER_1=IDENTIFIER_2&gt;"><a id="IDENTIFIER_1-IDENTIFIER_2"></a><code>&lt;IDENTIFIER_1=IDENTIFIER_2&gt;</code></dt>
<dd>

<p>Call the subrule whose name is IDENTIFIER_1.</p>

<p>If it matches successfully, save the hash it returns in the current scope&#39;s result-hash, under the key <code>&#39;IDENTIFIER_2&#39;</code>.</p>

<p>In other words, the <code>IDENTIFIER_1=</code> prefix changes the key under which the result of calling a subrule is stored.</p>

</dd>
<dt id="&lt;.IDENTIFIER&gt;"><a id="IDENTIFIER1"></a><code>&lt;.IDENTIFIER&gt;</code></dt>
<dd>

<p>Call the subrule whose name is IDENTIFIER. Don&#39;t save the hash it returns.</p>

<p>In other words, the &quot;dot&quot; prefix disables saving of subrule results.</p>

</dd>
<dt id="&lt;IDENTIFIER=-(-PATTERN-)&gt;"><a id="IDENTIFIER----PATTERN"></a><code>&lt;IDENTIFIER= ( PATTERN )&gt;</code></dt>
<dd>

<p>Match the subpattern PATTERN.</p>

<p>If it matches successfully, capture the substring it matched and save that substring in the current scope&#39;s result-hash, under the key &#39;IDENTIFIER&#39;.</p>

</dd>
<dt id="&lt;.IDENTIFIER=-(-PATTERN-)&gt;"><a id="IDENTIFIER----PATTERN1"></a><code>&lt;.IDENTIFIER= ( PATTERN )&gt;</code></dt>
<dd>

<p>Match the subpattern PATTERN. Don&#39;t save the substring it matched.</p>

</dd>
<dt id="&lt;IDENTIFIER=-%HASH&gt;"><a id="IDENTIFIER---HASH"></a><code>&lt;IDENTIFIER= %HASH&gt;</code></dt>
<dd>

<p>Match a sequence of non-whitespace then verify that the sequence is a key in the specified hash</p>

<p>If it matches successfully, capture the sequence it matched and save that substring in the current scope&#39;s result-hash, under the key &#39;IDENTIFIER&#39;.</p>

</dd>
<dt id="&lt;%HASH&gt;"><a id="HASH"></a><code>&lt;%HASH&gt;</code></dt>
<dd>

<p>Match a key from the hash. Don&#39;t save the substring it matched.</p>

</dd>
<dt id="&lt;IDENTIFIER=-(?{-CODE-})&gt;"><a id="IDENTIFIER----CODE"></a><code>&lt;IDENTIFIER= (?{ CODE })&gt;</code></dt>
<dd>

<p>Execute the specified CODE.</p>

<p>Save the result (of the final expression that the CODE evaluates) in the current scope&#39;s result-hash, under the key <code>&#39;IDENTIFIER&#39;</code>.</p>

</dd>
<dt id="&lt;[IDENTIFIER]&gt;"><a id="IDENTIFIER2"></a><code>&lt;[IDENTIFIER]&gt;</code></dt>
<dd>

<p>Call the subrule whose name is IDENTIFIER.</p>

<p>If it matches successfully, append the hash it returns to a nested array within the current scope&#39;s result-hash, under the key &lt;&#39;IDENTIFIER&#39;&gt;.</p>

</dd>
<dt id="&lt;[IDENTIFIER_1=IDENTIFIER_2]&gt;"><a id="IDENTIFIER_1-IDENTIFIER_21"></a><code>&lt;[IDENTIFIER_1=IDENTIFIER_2]&gt;</code></dt>
<dd>

<p>Call the subrule whose name is IDENTIFIER_1.</p>

<p>If it matches successfully, append the hash it returns to a nested array within the current scope&#39;s result-hash, under the key <code>&#39;IDENTIFIER_2&#39;</code>.</p>

</dd>
<dt id="&lt;ANY_SUBRULE&gt;+-%-&lt;ANY_OTHER_SUBRULE&gt;"><a id="ANY_SUBRULE-----ANY_OTHER_SUBRULE"></a><code>&lt;ANY_SUBRULE&gt;+ % &lt;ANY_OTHER_SUBRULE&gt;</code></dt>
<dd>

</dd>
<dt id="&lt;ANY_SUBRULE&gt;*-%-&lt;ANY_OTHER_SUBRULE&gt;"><a id="ANY_SUBRULE-----ANY_OTHER_SUBRULE1"></a><code>&lt;ANY_SUBRULE&gt;* % &lt;ANY_OTHER_SUBRULE&gt;</code></dt>
<dd>

</dd>
<dt id="&lt;ANY_SUBRULE&gt;+-%-(PATTERN)"><a id="ANY_SUBRULE-----PATTERN"></a><code>&lt;ANY_SUBRULE&gt;+ % (PATTERN)</code></dt>
<dd>

</dd>
<dt id="&lt;ANY_SUBRULE&gt;*-%-(PATTERN)"><a id="ANY_SUBRULE-----PATTERN1"></a><code>&lt;ANY_SUBRULE&gt;* % (PATTERN)</code></dt>
<dd>

<p>Repeatedly call the first subrule. Keep matching as long as the subrule matches, provided successive matches are separated by matches of the second subrule or the pattern.</p>

<p>In other words, match a list of ANY_SUBRULE&#39;s separated by ANY_OTHER_SUBRULE&#39;s or PATTERN&#39;s.</p>

<p>Note that, if a pattern is used to specify the separator, it must be specified in some kind of matched parentheses. These may be capturing [<code>(...)</code>], non-capturing [<code>(?:...)</code>], non-backtracking [<code>(?&gt;...)</code>], or any other construct enclosed by an opening and closing paren.</p>

</dd>
<dt id="&lt;ANY_SUBRULE&gt;+-%%-&lt;ANY_OTHER_SUBRULE&gt;"><a id="ANY_SUBRULE-----ANY_OTHER_SUBRULE2"></a><code>&lt;ANY_SUBRULE&gt;+ %% &lt;ANY_OTHER_SUBRULE&gt;</code></dt>
<dd>

</dd>
<dt id="&lt;ANY_SUBRULE&gt;*-%%-&lt;ANY_OTHER_SUBRULE&gt;"><a id="ANY_SUBRULE-----ANY_OTHER_SUBRULE3"></a><code>&lt;ANY_SUBRULE&gt;* %% &lt;ANY_OTHER_SUBRULE&gt;</code></dt>
<dd>

</dd>
<dt id="&lt;ANY_SUBRULE&gt;+-%%-(PATTERN)"><a id="ANY_SUBRULE-----PATTERN2"></a><code>&lt;ANY_SUBRULE&gt;+ %% (PATTERN)</code></dt>
<dd>

</dd>
<dt id="&lt;ANY_SUBRULE&gt;*-%%-(PATTERN)"><a id="ANY_SUBRULE-----PATTERN3"></a><code>&lt;ANY_SUBRULE&gt;* %% (PATTERN)</code></dt>
<dd>

<p>Repeatedly call the first subrule. Keep matching as long as the subrule matches, provided successive matches are separated by matches of the second subrule or the pattern.</p>

<p>Also allow an optional final trailing instance of the second subrule or pattern (this is where <code>%%</code> differs from <code>%</code>).</p>

<p>In other words, match a list of ANY_SUBRULE&#39;s separated by ANY_OTHER_SUBRULE&#39;s or PATTERN&#39;s, with a possible final separator.</p>

<p>As for the single <code>%</code> operator, if a pattern is used to specify the separator, it must be specified in some kind of matched parentheses. These may be capturing [<code>(...)</code>], non-capturing [<code>(?:...)</code>], non-backtracking [<code>(?&gt;...)</code>], or any other construct enclosed by an opening and closing paren.</p>

</dd>
</dl>

<h2 id="Special-variables-within-grammar-actions"><a id="Special"></a>Special variables within grammar actions</h2>

<dl>

<dt id="$CAPTURE"><a id="CAPTURE"></a><code>$CAPTURE</code></dt>
<dd>

</dd>
<dt id="$CONTEXT"><a id="CONTEXT"></a><code>$CONTEXT</code></dt>
<dd>

<p>These are both aliases for the built-in read-only <code>$^N</code> variable, which always contains the substring matched by the nearest preceding <code>(...)</code> capture. <code>$^N</code> still works perfectly well, but these are provided to improve the readability of code blocks and error messages respectively.</p>

</dd>
<dt id="$INDEX"><a id="INDEX"></a><code>$INDEX</code></dt>
<dd>

<p>This variable contains the index at which the next match will be attempted within the string being parsed. It is most commonly used in <code>&lt;error:...&gt;</code> or <code>&lt;log:...&gt;</code> directives:</p>

<pre><code>    &lt;rule: ListElem&gt;
        &lt;log: (?{ &quot;Trying words at index $INDEX&quot; })&gt;
        &lt;MATCH=( \w++ )&gt;
      |
        &lt;log: (?{ &quot;Trying digits at index $INDEX&quot; })&gt;
        &lt;MATCH=( \d++ )&gt;
      |
        &lt;error: (?{ &quot;Missing ListElem near index $INDEX&quot; })&gt;</code></pre>

</dd>
<dt id="%MATCH"><a id="MATCH"></a><code>%MATCH</code></dt>
<dd>

<p>This variable contains all the saved results of any subrules called from the current rule. In other words, subrule calls like:</p>

<pre><code>    &lt;ListElem&gt;  &lt;Separator= (,)&gt;</code></pre>

<p>stores their respective match results in <code>$MATCH{&#39;ListElem&#39;}</code> and <code>$MATCH{&#39;Separator&#39;}</code>.</p>

</dd>
<dt id="$MATCH"><a id="MATCH1"></a><code>$MATCH</code></dt>
<dd>

<p>This variable is an alias for <code>$MATCH{&quot;=&quot;}</code>. This is the <code>%MATCH</code> entry for the special &quot;override value&quot;. If this entry is defined, its value overrides the usual &quot;return \%MATCH&quot; semantics of a successful rule.</p>

</dd>
<dt id="%ARG"><a id="ARG"></a><code>%ARG</code></dt>
<dd>

<p>This variable contains all the key/value pairs that were passed into a particular subrule call.</p>

<pre><code>    &lt;Keyword&gt;  &lt;Command&gt;  &lt;Terminator(:Keyword)&gt;</code></pre>

<p>the <code>Terminator</code> rule could get access to the text matched by <code>&lt;Keyword&gt;</code> like so:</p>

<pre><code>    &lt;token: Terminator&gt;
        end_ (??{ $ARG{&#39;Keyword&#39;} })</code></pre>

<p>Note that to match against the calling subrules &#39;Keyword&#39; value, it&#39;s necessary to use either a deferred interpolation (<code>(??{...})</code>) or a qualified matchref:</p>

<pre><code>    &lt;token: Terminator&gt;
        end_ &lt;\:Keyword&gt;</code></pre>

<p>A common mistake is to attempt to directly interpolate the argument:</p>

<pre><code>    &lt;token: Terminator&gt;
        end_ $ARG{&#39;Keyword&#39;}</code></pre>

<p>This evaluates <code>$ARG{&#39;Keyword&#39;}</code> when the grammar is compiled, rather than when the rule is matched.</p>

</dd>
<dt id="$_"><a id="pod2"></a><code>$_</code></dt>
<dd>

<p>At the start of any code blocks inside any regex, the variable <code>$_</code> contains the complete string being matched against. The current matching position within that string is given by: <code>pos($_)</code>.</p>

</dd>
<dt id="$DEBUG"><a id="DEBUG"></a><code>$DEBUG</code></dt>
<dd>

<p>This variable stores the current debugging mode (which may be any of: <code>&#39;off&#39;</code>, <code>&#39;on&#39;</code>, <code>&#39;run&#39;</code>, <code>&#39;continue&#39;</code>, <code>&#39;match&#39;</code>, <code>&#39;step&#39;</code>, or <code>&#39;try&#39;</code>). It is set automatically by the <code>&lt;debug:...&gt;</code> command, but may also be set manually in a code block (which can be useful for conditional debugging). For example:</p>

<pre><code>    &lt;rule: ListElem&gt;
        &lt;Identifier&gt;

        # Conditionally debug if &#39;foobar&#39; encountered...
        (?{ $DEBUG = $MATCH{Identifier} eq &#39;foobar&#39; ? &#39;step&#39; : &#39;off&#39; })

        &lt;Modifier&gt;?</code></pre>

<p>See also: the <code>&lt;log: LOGFILE&gt;</code> and <code>&lt;debug: DEBUG_CMD&gt;</code> directives.</p>

</dd>
</dl>

<h1 id="IMPORTANT-CONSTRAINTS-AND-LIMITATIONS"><a id="IMPORTANT"></a>IMPORTANT CONSTRAINTS AND LIMITATIONS</h1>

<ul>

<li><p>Prior to Perl 5.14, the Perl 5 regex engine as not reentrant. So any attempt to perform a regex match inside a <code>(?{ ... })</code> or <code>(??{ ... })</code> under Perl 5.12 or earlier will almost certainly lead to either weird data corruption or a segfault.</p>

<p>The same calamities can also occur in any constructor called by <code>&lt;objrule:&gt;</code>. If the constructor invokes another regex in any way, it will most likely fail catastrophically. In particular, this means that Moose constructors will frequently crash and burn within a Regex::Grammars grammar (for example, if the Moose-based class declares an attribute type constraint such as &#39;Int&#39;, which Moose checks using a regex).</p>

</li>
<li><p>The additional regex constructs this module provides are implemented by rewriting regular expressions. This is a (safer) form of source filtering, but still subject to all the same limitations and fallibilities of any other macro-based solution.</p>

</li>
<li><p>In particular, rewriting the macros involves the insertion of (a lot of) extra capturing parentheses. This means you can no longer assume that particular capturing parens correspond to particular numeric variables: i.e. to <code>$1</code>, <code>$2</code>, <code>$3</code> etc. If you want to capture directly use Perl 5.10&#39;s named capture construct:</p>

<pre><code>    (?&lt;name&gt; [^\W\d]\w* )</code></pre>

<p>Better still, capture the data in its correct hierarchical context using the module&#39;s &quot;named subpattern&quot; construct:</p>

<pre><code>    &lt;name= ([^\W\d]\w*) &gt;</code></pre>

</li>
<li><p>No recursive descent parser--including those created with Regexp::Grammars--can directly handle left-recursive grammars with rules of the form:</p>

<pre><code>    &lt;rule: List&gt;
        &lt;List&gt; , &lt;ListElem&gt;</code></pre>

<p>If you find yourself attempting to write a left-recursive grammar (which Perl 5.10 may or may not complain about, but will never successfully parse with), then you probably need to use the &quot;separated list&quot; construct instead:</p>

<pre><code>    &lt;rule: List&gt;
        &lt;[ListElem]&gt;+ % (,)</code></pre>

</li>
<li><p>Grammatical parsing with Regexp::Grammars can fail if your grammar uses &quot;non-backtracking&quot; directives (i.e. the <code>(?&gt;...)</code> block or the <code>?+</code>, <code>*+</code>, or <code>++</code> repetition specifiers). The problem appears to be that preventing the regex from backtracking through the in-regex actions that Regexp::Grammars adds causes the module&#39;s internal stack to fall out of sync with the regex match.</p>

<p>For the time being, if your grammar does not work as expected, you may need to replace one or more &quot;non-backtracking&quot; directives, with their regular (i.e. backtracking) equivalents.</p>

</li>
<li><p>Similarly, parsing with Regexp::Grammars will fail if your grammar places a subrule call within a positive look-ahead, since these don&#39;t play nicely with the data stack.</p>

<p>This seems to be an internal problem with perl itself. Investigations, and attempts at a workaround, are proceeding.</p>

<p>For the time being, you need to make sure that grammar rules don&#39;t appear inside a positive lookahead or use the <a href="https://metacpan.org/pod/&#32;&quot;Lookahead&#32;(zero-width)&#32;subrules&quot;"><code>&lt;?RULENAME&gt;</code> construct </a> instead</p>

</li>
</ul>

<h1 id="DIAGNOSTICS">DIAGNOSTICS</h1>

<p>Note that (because the author cannot find a way to throw exceptions from within a regex) none of the following diagnostics actually throws an exception.</p>

<p>Instead, these messages are simply written to the specified parser logfile (or to <code>*STDERR</code>, if no logfile is specified).</p>

<p>However, any fatal match-time message will immediately terminate the parser matching and will still set <code>$@</code> (as if an exception had been thrown and caught at that point in the code). You then have the option to check <code>$@</code> immediately after matching with the grammar, and rethrow if necessary:</p>

<pre><code>    if ($input =~ $grammar) {
        process_data_in(\%/);
    }
    else {
        die if $@;
    }</code></pre>

<dl>

<dt id="Found-call-to-%s,-but-no-%s-was-defined-in-the-grammar"><a id="Found"></a><a id="Found-call-to--s--but-no--s-was-defined-in-the-grammar"></a><code>Found call to %s, but no %s was defined in the grammar</code></dt>
<dd>

<p>You specified a call to a subrule for which there was no definition in the grammar. Typically that&#39;s either because you forget to define the rule, or because you misspelled either the definition or the subrule call. For example:</p>

<pre><code>    &lt;file&gt;

    &lt;rule: fiel&gt;            &lt;---- misspelled rule
        &lt;lines&gt;             &lt;---- used but never defined</code></pre>

<p>Regexp::Grammars converts any such subrule call attempt to an instant catastrophic failure of the entire parse, so if your parser ever actually tries to perform that call, Very Bad Things will happen.</p>

</dd>
<dt id="Entire-parse-terminated-prematurely-while-attempting-to-call-non-existent-rule:-%s"><a id="Entire"></a><a id="Entire-parse-terminated-prematurely-while-attempting-to-call-non-existent-rule:--s"></a><code>Entire parse terminated prematurely while attempting to call non-existent rule: %s</code></dt>
<dd>

<p>You ignored the previous error and actually tried to call to a subrule for which there was no definition in the grammar. Very Bad Things are now happening. The parser got very upset, took its ball, and went home. See the preceding diagnostic for remedies.</p>

<p>This diagnostic should throw an exception, but can&#39;t. So it sets <code>$@</code> instead, allowing you to trap the error manually if you wish.</p>

</dd>
<dt id="Fatal-error:-&lt;objrule:-%s&gt;-returned-a-non-hash-based-object"><a id="Fatal"></a><a id="Fatal-error:--objrule:--s--returned-a-non-hash-based-object"></a><code>Fatal error: &lt;objrule: %s&gt; returned a non-hash-based object</code></dt>
<dd>

<p>An &lt;objrule:&gt; was specified and returned a blessed object that wasn&#39;t a hash. This will break the behaviour of the grammar, so the module immediately reports the problem and gives up.</p>

<p>The solution is to use only hash-based classes with &lt;objrule:&gt;</p>

</dd>
<dt id="Can&#39;t-match-against-&lt;grammar:-%s&gt;"><a id="Can"></a><a id="Can-t-match-against--grammar:--s"></a><code>Can&#39;t match against &lt;grammar: %s&gt;</code></dt>
<dd>

<p>The regex you attempted to match against defined a pure grammar, using the <code>&lt;grammar:...&gt;</code> directive. Pure grammars have no start-pattern and hence cannot be matched against directly.</p>

<p>You need to define a matchable grammar that inherits from your pure grammar and then calls one of its rules. For example, instead of:</p>

<pre><code>    my $greeting = qr{
        &lt;grammar: Greeting&gt;

        &lt;rule: greet&gt;
            Hi there
            | Hello
            | Yo!
    }xms;</code></pre>

<p>you need:</p>

<pre><code>    qr{
        &lt;grammar: Greeting&gt;

        &lt;rule: greet&gt;
            Hi there
          | Hello
          | Yo!
    }xms;

    my $greeting = qr{
        &lt;extends: Greeting&gt;
        &lt;greet&gt;
    }xms;</code></pre>

</dd>
<dt id="Inheritance-from-unknown-grammar-requested-by-&lt;%s&gt;"><a id="Inheritance"></a><a id="Inheritance-from-unknown-grammar-requested-by--s"></a><code>Inheritance from unknown grammar requested by &lt;%s&gt;</code></dt>
<dd>

<p>You used an <code>&lt;extends:...&gt;</code> directive to request that your grammar inherit from another, but the grammar you asked to inherit from doesn&#39;t exist.</p>

<p>Check the spelling of the grammar name, and that it&#39;s already been defined somewhere earlier in your program.</p>

</dd>
<dt id="Redeclaration-of-&lt;%s&gt;-will-be-ignored"><a id="Redeclaration"></a><a id="Redeclaration-of--s--will-be-ignored"></a><code>Redeclaration of &lt;%s&gt; will be ignored</code></dt>
<dd>

<p>You defined two or more rules or tokens with the same name. The first one defined in the grammar will be used; the rest will be ignored.</p>

<p>To get rid of the warning, get rid of the extra definitions (or, at least, comment them out or rename the rules).</p>

</dd>
<dt id="Possible-invalid-subrule-call-%s"><a id="Possible"></a><a id="Possible-invalid-subrule-call--s"></a><code>Possible invalid subrule call %s</code></dt>
<dd>

<p>Your grammar contained something of the form:</p>

<pre><code>    &lt;identifier
    &lt;.identifier
    &lt;[identifier</code></pre>

<p>which you might have intended to be a subrule call, but which didn&#39;t correctly parse as one. If it was supposed to be a Regexp::Grammars subrule call, you need to check the syntax you used. If it wasn&#39;t supposed to be a subrule call, you can silence the warning by rewriting it and quoting the leading angle:</p>

<pre><code>    \&lt;identifier
    \&lt;.identifier
    \&lt;[identifier</code></pre>

</dd>
<dt id="Possible-failed-attempt-to-specify-a-subrule-call-or-directive:-%s"><a id="Possible1"></a><a id="Possible-failed-attempt-to-specify-a-subrule-call-or-directive:--s"></a><code>Possible failed attempt to specify a subrule call or directive: %s</code></dt>
<dd>

<p>Your grammar contained something of the form:</p>

<pre><code>    &lt;identifier...</code></pre>

<p>but which wasn&#39;t a call to a known subrule or directive. If it was supposed to be a subrule call, check the spelling of the rule name in the angles. If it was supposed to be a Regexp::Grammars directive, check the spelling of the directive name. If it wasn&#39;t supposed to be a subrule call or directive, you can silence the warning by rewriting it and quoting the leading angle:</p>

<pre><code>    \&lt;identifier</code></pre>

</dd>
<dt id="Invalid-&lt;-metacharacter"><a id="Invalid"></a><a id="Invalid---metacharacter"></a><code>Invalid &lt; metacharacter</code></dt>
<dd>

<p>The <code>&lt;</code> character is always special in Regexp::Grammars regexes: it either introduces a subrule call, or a rule/token declaration, or a directive.</p>

<p>If you need to match a literal <code>&#39;&lt;&#39;</code>, use <code>\&lt;</code> in your regex.</p>

</dd>
<dt id="Invalid-separation-specifier:-%s"><a id="Invalid1"></a><a id="Invalid-separation-specifier:--s"></a><code>Invalid separation specifier: %s</code></dt>
<dd>

<p>You used a <code>%</code> or a <code>%%</code> in the regex, but in a way that won&#39;t do what you expect. <code>%</code> and <code>%%</code> are metacharacters in Regexp::Grammars regexes, and can only be placed between a repeated atom (that matches a list of items) and a simple atom (that matches the separator between list items). See <a href="./Regexp::Grammars.html#Matching-separated-lists">&quot;Matching separated lists&quot;</a>.</p>

<p>If you were using <code>%</code> or <code>%%</code> as a metacharacter, then you either forgot the repetition quantifier (<code>*</code>, <code>+</code>, <code>{0,9}</code>, etc.) on the preceding list-matching atom, or you specified the following separator atom as something too complex for the module to parse (for example, a set of parens with nested subrule calls).</p>

<p>On the other hand, if you were intending to match a literal <code>%</code> or <code>%%</code> within a Regexp::Grammars regex, then you must explicitly specify it as being a literal by quotemeta&#39;ing it, like so: <code>\%</code> or <code>\%\%</code></p>

</dd>
<dt id="Repeated-subrule-%s-will-only-capture-its-final-match"><a id="Repeated"></a><a id="Repeated-subrule--s-will-only-capture-its-final-match"></a><code>Repeated subrule %s will only capture its final match</code></dt>
<dd>

<p>You specified a subrule call with a repetition qualifier, such as:</p>

<pre><code>    &lt;ListElem&gt;*</code></pre>

<p>or:</p>

<pre><code>    &lt;ListElem&gt;+</code></pre>

<p>Because each subrule call saves its result in a hash entry of the same name, each repeated match will overwrite the previous ones, so only the last match will ultimately be saved. If you want to save all the matches, you need to tell Regexp::Grammars to save the sequence of results as a nested array within the hash entry, like so:</p>

<pre><code>    &lt;[ListElem]&gt;*</code></pre>

<p>or:</p>

<pre><code>    &lt;[ListElem]&gt;+</code></pre>

<p>If you really did intend to throw away every result but the final one, you can silence the warning by placing the subrule call inside any kind of parentheses. For example:</p>

<pre><code>    (&lt;ListElem&gt;)*</code></pre>

<p>or:</p>

<pre><code>    (?: &lt;ListElem&gt; )+</code></pre>

</dd>
<dt id="Unable-to-open-log-file-&#39;$filename&#39;-(%s)"><a id="Unable"></a><a id="Unable-to-open-log-file--filename---s"></a><code>Unable to open log file &#39;$filename&#39; (%s)</code></dt>
<dd>

<p>You specified a <code>&lt;logfile:...&gt;</code> directive but the file whose name you specified could not be opened for writing (for the reason given in the parens).</p>

<p>Did you misspell the filename, or get the permissions wrong somewhere in the filepath?</p>

</dd>
<dt id="Non-backtracking-subrule-%s-may-not-revert-correctly-during-backtracking"><a id="Non"></a><a id="Non-backtracking-subrule--s-may-not-revert-correctly-during-backtracking"></a><code>Non-backtracking subrule %s may not revert correctly during backtracking</code></dt>
<dd>

<p>Because of inherent limitations in the Perl regex engine, non-backtracking constructs like <code>++</code>, <code>*+</code>, <code>?+</code>, and <code>(?&gt;...)</code> do not always work correctly when applied to subrule calls, especially in earlier versions of Perl.</p>

<p>If the grammar doesn&#39;t work properly, replace the offending constructs with regular backtracking versions instead. If the grammar does work, you can silence the warning by enclosing the subrule call in any kind of parentheses. For example, change:</p>

<pre><code>    &lt;[ListElem]&gt;++</code></pre>

<p>to:</p>

<pre><code>    (?: &lt;[ListElem]&gt; )++</code></pre>

</dd>
<dt id="Unexpected-item-before-first-subrule-specification-in-definition-of-&lt;grammar:-%s&gt;"><a id="Unexpected"></a><a id="Unexpected-item-before-first-subrule-specification-in-definition-of--grammar:--s"></a><code>Unexpected item before first subrule specification in definition of &lt;grammar: %s&gt;</code></dt>
<dd>

<p>Named grammar definitions must consist only of rule and token definitions. They cannot have patterns before the first definitions. You had some kind of pattern before the first definition, which will be completely ignored within the grammar.</p>

<p>To silence the warning, either comment out or delete whatever is before the first rule/token definition.</p>

</dd>
<dt id="No-main-regex-specified-before-rule-definitions"><a id="No"></a><code>No main regex specified before rule definitions</code></dt>
<dd>

<p>You specified an unnamed grammar (i.e. no <code>&lt;grammar:...&gt;</code> directive), but didn&#39;t specify anything for it to actually match, just some rules that you don&#39;t actually call. For example:</p>

<pre><code>    my $grammar = qr{

        &lt;rule: list&gt;    \( &lt;item&gt; +% [,] \)

        &lt;token: item&gt;   &lt;list&gt; | \d+
    }x;</code></pre>

<p>You have to provide something before the first rule to start the matching off. For example:</p>

<pre><code>    my $grammar = qr{

        &lt;list&gt;   # &lt;--- This tells the grammar how to start matching

        &lt;rule: list&gt;    \( &lt;item&gt; +% [,] \)

        &lt;token: item&gt;   &lt;list&gt; | \d+
    }x;</code></pre>

</dd>
<dt id="Ignoring-useless-empty-&lt;ws:&gt;-directive"><a id="Ignoring"></a><a id="Ignoring-useless-empty--ws:--directive"></a><code>Ignoring useless empty &lt;ws:&gt; directive</code></dt>
<dd>

<p>The <code>&lt;ws:...&gt;</code> directive specifies what whitespace matches within the current rule. An empty <code>&lt;ws:&gt;</code> directive would cause whitespace to match nothing at all, which is what happens in a token definition, not in a rule definition.</p>

<p>Either put some subpattern inside the empty <code>&lt;ws:...&gt;</code> or, if you really do want whitespace to match nothing at all, remove the directive completely and change the rule definition to a token definition.</p>

</dd>
<dt id="Ignoring-useless-&lt;ws:-%s-&gt;-directive-in-a-token-definition"><a id="Ignoring1"></a><a id="Ignoring-useless--ws:--s---directive-in-a-token-definition"></a><code>Ignoring useless &lt;ws: %s &gt; directive in a token definition</code></dt>
<dd>

<p>The <code>&lt;ws:...&gt;</code> directive is used to specify what whitespace matches within a rule. Since whitespace never matches anything inside tokens, putting a <code>&lt;ws:...&gt;</code> directive in a token is a waste of time.</p>

<p>Either remove the useless directive, or else change the surrounding token definition to a rule definition.</p>

</dd>
<dt id="Quantifier-that-doesn&#39;t-quantify-anything:-&lt;%s&gt;"><a id="Quantifier"></a><a id="Quantifier-that-doesn-t-quantify-anything:--s"></a><code>Quantifier that doesn&#39;t quantify anything: &lt;%s&gt;</code></dt>
<dd>

<p>You specified a rule or token something like:</p>

<pre><code>    &lt;token: star&gt;  *</code></pre>

<p>or:</p>

<pre><code>    &lt;rule: add_op&gt;  plus | add | +</code></pre>

<p>but the <code>*</code> and <code>+</code> in those examples are both regex meta-operators: quantifiers that usually cause what precedes them to match repeatedly. In these cases however, nothing is preceding the quantifier, so it&#39;s a Perl syntax error.</p>

<p>You almost certainly need to escape the meta-characters in some way. For example:</p>

<pre><code>    &lt;token: star&gt;  \*

    &lt;rule: add_op&gt;  plus | add | [+]</code></pre>

</dd>
</dl>

<h1 id="CONFIGURATION-AND-ENVIRONMENT"><a id="CONFIGURATION"></a>CONFIGURATION AND ENVIRONMENT</h1>

<p>Regexp::Grammars requires no configuration files or environment variables.</p>

<h1 id="DEPENDENCIES">DEPENDENCIES</h1>

<p>This module only works under Perl 5.10 or later.</p>

<h1 id="INCOMPATIBILITIES">INCOMPATIBILITIES</h1>

<p>This module is likely to be incompatible with any other module that automagically rewrites regexes. For example it may conflict with Regexp::DefaultFlags, Regexp::DeferredExecution, or Regexp::Extended.</p>

<h1 id="BUGS">BUGS</h1>

<p>No bugs have been reported.</p>

<p>Please report any bugs or feature requests to <code>bug-regexp-grammars@rt.cpan.org</code>, or through the web interface at <a href="http://rt.cpan.org">http://rt.cpan.org</a>.</p>

<h1 id="CONTRIBUTING">CONTRIBUTING</h1>

<p>Patches and other similar contributions are always welcome.</p>

<p>For more details on how best to contribute improvements to this module, see <a href="https://metacpan.org/dist/Regexp-Grammars/contribute">https://metacpan.org/dist/Regexp-Grammars/contribute</a> or the CONTRIBUTING file in the module&#39;s distribution.</p>

<h1 id="AUTHOR">AUTHOR</h1>

<p>Damian Conway <code>&lt;DCONWAY@CPAN.org&gt;</code></p>

<h1 id="LICENCE-AND-COPYRIGHT"><a id="LICENCE"></a>LICENCE AND COPYRIGHT</h1>

<p>Copyright (c) 2009, Damian Conway <code>&lt;DCONWAY@CPAN.org&gt;</code>. All rights reserved.</p>

<p>This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See <a href="https://metacpan.org/pod/perlartistic">perlartistic</a>.</p>

<h1 id="DISCLAIMER-OF-WARRANTY"><a id="DISCLAIMER"></a>DISCLAIMER OF WARRANTY</h1>

<p>BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE &quot;AS IS&quot; WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.</p>

<p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</p></div>

<div id="metacpan_install-instructions-dialog" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title">Module Install Instructions</h4>
      </div>
      <div class="modal-body">
        <p>To install Regexp::Grammars, copy and paste the appropriate command in to your terminal.</p>
        <p><a href="https://metacpan.org/dist/App-cpanminus/view/bin/cpanm">cpanm</a></p>
        <pre><code>cpanm Regexp::Grammars</code></pre>
        <p><a href="https://metacpan.org/pod/CPAN">CPAN shell</a></p>
        <pre><code>perl -MCPAN -e shell
install Regexp::Grammars</code></pre>
        <p>For more information on module installation, please visit <a href="https://www.cpan.org/modules/INSTALL.html">the detailed CPAN module installation guide</a>.</p>
      </div>
      <div class="modal-footer">
        <a href="./Regexp::Grammars.html#" data-dismiss="modal" class="btn">Close</a>
      </div>
    </div>
  </div>
</div>
          </main>
          <div class="content-pagination">
          </div>
        </div>
        <footer class="footer">
          <div class="footer-container">
            <div class="footer-social">
              <div class="footer-link footer-logo">
                <a href="https://metacpan.org/">
                  <img src="https://metacpan.org/static/images/metacpan-logo.svg" alt="MetaCPAN" />
                </a>
              </div>
              <a class="footer-social-link" href="https://github.com/metacpan">
                <i class="fab fa-github-square"></i>
              </a>
              <a class="footer-social-link" href="https://fosstodon.org/@metacpan">
                <i class="fab fa-mastodon"></i>
              </a>
            </div>
            <div class="footer-links">
              <div class="footer-link">
                  <a href="https://metacpan.org/about">About</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/about/sponsors">Sponsor</a>
              </div>
              <div class="footer-link">
                  <a href="https://grep.metacpan.org">grep::cpan</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/recent">Recent</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/about/faq">FAQ</a>
              </div>
              <div class="footer-link">
                  <a href="https://metacpan.org/tools">Tools</a>
              </div>
              <div class="footer-link">
                  <a href="https://fastapi.metacpan.org/">API</a>
              </div>
              <div class="footer-link">
                  <a href="https://www.perl.org/">Perl.org</a>
              </div>
            </div>
            <div class="footer-sponsors">
              <a class="footer-sponsor-link" target="_blank" href="https://www.bytemark.co.uk/" rel="noopener">
                <img class="footer-sponsor-bytemark" src="https://metacpan.org/static/images/sponsors/bytemark_logo.svg" alt="Bytemark logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://www.liquidweb.com/" rel="noopener">
                <img class="footer-sponsor-liquidweb" src="https://metacpan.org/static/images/sponsors/liquidweb_logo.png" alt="liquidweb logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://deriv.com/careers/" rel="noopener">
                <img class="footer-sponsor-deriv" src="https://metacpan.org/static/images/sponsors/deriv.svg" alt="Deriv logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://geocode.xyz" rel="noopener">
                <img class="footer-sponsor-geocode" src="https://metacpan.org/static/images/sponsors/geocodelogo.svg" alt="Geocode logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://www.fastly.com/" rel="noopener">
                <img class="footer-sponsor-fastly" src="https://metacpan.org/static/images/sponsors/fastly_logo.svg" alt="Fastly logo">
              </a>
              <a class="footer-sponsor-link" target="_blank" href="https://opencagedata.com" rel="noopener">
                <img class="footer-sponsor-opencage" src="https://metacpan.org/static/images/sponsors/open-cage.svg" alt="OpenCage logo">
              </a>
            </div>
          </div>
        </footer>
        <div class="modal fade" tabindex="-1" role="dialog" id="metacpan_keyboard-shortcuts">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Keyboard Shortcuts</h4>
              </div>
              <div class="modal-body row">
<div class="col-md-6">
  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>Global</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="keys">
          <kbd>s</kbd>
        </td>
        <td>Focus search bar</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>?</kbd>
        </td>
        <td>Bring up this help dialog</td>
      </tr>
    </tbody>
  </table>

  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>GitHub</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>p</kbd>
        </td>
        <td>Go to pull requests</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>i</kbd>
        </td>
        <td>go to github issues (only if github is preferred repository)</td>
      </tr>
    </tbody>
  </table>
</div>

<div class="col-md-6">
  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>POD</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>a</kbd>
        </td>
        <td>Go to author</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>c</kbd>
        </td>
        <td>Go to changes</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>i</kbd>
        </td>
        <td>Go to issues</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>d</kbd>
        </td>
        <td>Go to dist</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>r</kbd>
        </td>
        <td>Go to repository/SCM</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>s</kbd>
        </td>
        <td>Go to source</td>
      </tr>
      <tr>
        <td class="keys">
          <kbd>g</kbd> <kbd>b</kbd>
        </td>
        <td>Go to file browse</td>
      </tr>

    </tbody>
  </table>
</div>

<div class="col-md-12">
  <table class="table keyboard-shortcuts">
    <thead>
      <tr>
        <th></th>
        <th>Search terms</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><em>module:</em> (e.g. <a href="https://metacpan.org/search?q=module%3APlugin">module:Plugin</a>)</td>
      </tr>
      <tr>
        <td><em>distribution:</em> (e.g. <a href="https://metacpan.org/search?q=distribution%3ADancer+auth">distribution:Dancer auth</a>)</td>
      </tr>
      <tr>
        <td><em>author:</em> (e.g. <a href="https://metacpan.org/search?q=author%3ASONGMU+Redis">author:SONGMU Redis</a>)</td>
      </tr>
      <tr>
        <td><em>version:</em> (e.g. <a href="https://metacpan.org/search?q=version%3A1.00">version:1.00</a>)</td>
      </tr>
    </tbody>
  </table>
</div>
              </div>
              <div class="modal-footer"></div>
            </div>
          </div>
        </div>
    </body>
</html>
